I was taking an online java course and given this question, my idea was to generate 2 random double(s) and subtract one from the other as each will produce a double between 0 and 1.
This program is to compute an estimate of pi by simulating dart throws onto a square.
The instructor answer was to multiply the generated double by 2 and subtract 1.
My question is, where those two ways differ?
Below is the instructor's answer:
public class MonteCarlo
{
public static void main(String[] args)
{
System.out.println("Number of tries");
Random generator = new Random(42);
Scanner in = new Scanner(System.in);
int tries = in.nextInt();
int hits = 0;
for (int i = 1; i <= tries; i++)
{
// Generate two random numbers between -1 and 1
double x = generator.nextDouble() * 2 -1 ;
double y = generator.nextDouble() * 2 -1 ;
// Check whether the point lies in the unit circle
if (Math.sqrt((x - 0) * (x - 0) + (y - 0) * (y - 0)) <= 1)
{
hits++;
}
}
/*
The ratio hits / tries is approximately the same as the ratio
circle area / square area = pi / 4
*/
double piEstimate = 4.0 * hits / tries;
System.out.println("Estimate for pi: " + piEstimate);
}
}
Aucun commentaire:
Enregistrer un commentaire