I came across this question in the Cay Horstmann book:
Program the following simulation: Darts are thrown at random points onto the square with corners (1,1) and (−1,−1). If the dart lands inside the unit circle (that is, the circle with center (0,0) and radius 1), it is a hit. Otherwise it is a miss. Run this simulation and use it to determine an approximate value for π. Extra credit if you explain why this is a better method for estimating π than the Buffon needle program.
I do get why this is a better method for estimating π than the Buffon needle program, so that is fine. But I seem to have problems with my code.
Here is my current code:
import java.util.Scanner;
public class Dart {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number of tries: ");
int n = in.nextInt();
int miss = 0;
int hit = 0;
double x = Math.random() * 2 - 1;
double y = Math.random() * 2 - 1;
double func = x * x + y * y;
for (int i = 0; i < n; i++) {
if (func <= 1) {
hit++;
} else {
miss++;
}
}
System.out.println("Probability: " + hit / (hit + miss) * 4);
}
}
When I enter any numbers, the Probability output always comes out as 1, but I think if the code is right it prints π because its: (the area of a circle with radius 1) over (a square with length 2) times 4.
I would appreciate an explanation why my code is wrong.