Using random to generate pi

It could look counterintuitive, but we can use a pseudo-random, uniformly distributed, sequence to find out pi. One could asks why on the Earth we should do something like that when any reasonable programming environment provides it off the box - in Java it is a constant in the Math class, Math.PI a double set to 3.14159265358979323846, as one could expect.

OK, forget about the how much it looks reasonable to calculate pi in this way, what it is interesting it is the general idea behind.

Think to a square with a circle inscribed in it. The area of the circle is pi*radius*radius. The area of the square is (2*radius)*(2*radius).

Now think to throw arrows to the square. Assuming the result is an homogeneous distribution, we should get that the ratio between the arrows inside the circle and all the arrows that reached the square should be the same of the ratio between the areas of the two figures.

So: pi*radius*radius / (2*radius)*(2*radius) = arrows in the circle / arrows in the square

It should be easy to get from that: pi = 4 * arrows in the circle / arrows in the square

Let's implement it in Java, simplifying it a bit working on just a quarter of the circle and square, so that we would use just values in the 0, 1 interval:
import java.util.Random;

public class RandomPi {
    private Random generator;

    public RandomPi() {
        generator = new Random(System.currentTimeMillis()); // 1
    } 

    public double pi(int n) { // 2
        int hit = 0;
        for(int i = 0; i < n; ++i) {
            double x = generator.nextDouble();
            double y = generator.nextDouble();

            if(Math.sqrt(x*x + y*y) < 1) // 3
                ++hit;
        }        
        return 4.0 * hit / n; // 4
    }
}
1. The random generator is initialized passing the current time, so to have a different sequence for each run of this application.
2. Our pi generator asks in input for the number of "arrows" that we throw. Be prepared of using an high value to get a reasonable approximation.
3. If the distance of the randomly generated coordinates from the center (0, 0) is less than 1, the arrow is in the circle, so we increase the counter.
4. We apply our formula, as seen above. We explicitly use 4 as a double value, otherwise we would have a division between integers, giving as result an integer, hardly what we really want.

No comments:

Post a Comment