Pi (π) is a mathematical thing of true beauty. It comes up in many equations, most notably in the equation for the area of a circle, the p.d.f. of a normal distribution and finally, and oh so wonderously, in Euler's Identity.

But how do we know that the value of π is 3.14159265359...? There are several ways to calculate pi. In this problem we show how to do it using darts.

This boy's name is also Pi. This problem is unrelated (other than name) to him.

Imagine throwing darts at the yellow circle bellow to the left. If you randomly throw a series of darts at the dartboard, some will land inside the yellow circle and some in the gray area outside it. If you count both the number of darts that fall inside the circle and the number that fall anywhere inside the square, the ratio of those numbers should be proportional to the relative area of the two figures.

Because the area of the circle is π and that of the square is 4, the fraction that falls inside the circle should approach π / 4.

Solution

/**
 * Find Pi
 * -------------
 * Find the value of pi by throwing random darts at a unit circle inscribed in
 * a square. The fraction that land in the circle should equal pi / 4.
 */
public class FindPi extends ConsoleProgram {
	
	private RandomGenerator rd = new RandomGenerator();
	
	public void run() {
		int numInCircle = 0;
		int numDarts = 50000000;
		for(int i = 0; i < numDarts; i++) {
			// get a random x, y in a 2x2
			double x = rd.nextDouble(-1, 1);
			double y = rd.nextDouble(-1, 1);
			// test if the dart landed in the circle
			double dist = Math.sqrt(x * x + y * y);
			if(dist <= 1) {
				numInCircle++;
			}
		}
		// if we don't cast to double, this will always be 0.
		double fraction = (double)numInCircle / numDarts;
		double pi = fraction * 4;
		print(pi);
	}
}