Reputation: 324
I was taking an online java course and given the following challenge:
Compute an estimate of π by simulating throwing darts onto the unit square and determining the fraction of them that lie in the unit circle.
My idea for how to generate the random x coordinate was to pick two uniformly-random numbers in the range [0, 1], then subtract them. The resulting values then range from -1 to +1.
The instructor answer was to multiply the generated double by 2 and subtract 1. Here's their code:
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);
}
}
My question is, how do my instructor's approach and my approach differ? Does my idea work?
Upvotes: 1
Views: 280
Reputation: 373032
This is actually more of a math question than a programming question. Your goal is to sample a uniformly-random real number in the range [-1, 1], and you have two ways of doing this:
Sample a real number in the range [0, 1], multiply it by two, and subtract one.
Sample two real numbers in the range [0, 1] uniformly, then subtract them.
Method (1) works correctly. Method (2) does not. Rather than explaining it for the range [0, 1], let's imagine instead you want to pick a random number between -5 and +5 by rolling two fair dice and subtracting the first die from the second. Even though every die roll is fair and uniformly picks something out of {1, 2, 3, 4, 5, 6}, the resulting distribution isn't uniform. For example:
The same mathematical sort of argument works out to explain why subtracting two uniformly-random numbers won't give you a uniformly-random distribution over the range you want. Instead, you'll get a triangularly-shaped distribution that's peaked at 0 and drops off as you go towards +1 and -1.
So in other words, you do get a random number - it just isn't equivalent to throwing a dart at the unit square with uniform probability.
Upvotes: 3