In Educating Essex there’s a clip where a student asks “What is π, where did it come from?”
Playing with processing.js today (with a sick little F for company) I came up with this. When I started it was based on a fuzzy memory of a distant NPR radio show. By the time I was finished I’d realised I’d stumbled into something of a classic.
Imagine a circle that is just contained within a square, actually, don’t imagine, here’s one drawn with the processing arc function:
How does this help find a value for π? Since the area of the circle is:
Circle Area = πr2
and the area of the rectangle enclosing the circle is:
Rectangle Area = 2r x 2r = 4r2
We know that π can be calculated by:
π = 4 (Circle Area / Square Area)
i.e. if we can calculate (or guess!) the area of the circle we can calculate π.
The normal way to calculate the area of a circle is to use the formula πr2 but since π is also what we want to know, we’ll need something different. Notice that we don’t actually need to know the areas, we just need the ratio of the area of the circle to the area of the square. That means that the something different we’re looking for is to find that ratio.
After some thought I decided to throw darts at the square in some random fashion (blindfolded will do) and to then count the number of darts that hit the circle. Knowing how many I’d thrown in total would give the ratio. Unfortunately, I found that throwing darts at a computer screen is a bad idea. They don’t ‘stick’ unless you throw them really hard. When you throw them really hard the picture disappears with a loud bang. Instead, I used processing.js to throw virtual darts:
// throw a virtual dart at position x,y and leave a point
x = random(1,width);
y = random(1,height);
I could then test whether each ‘dart’ hit the circle or not:
// test if dart hit inside the circle
// by calculating distance from origin…
a = (x – centreX);
asquared = a*a;
b = (y – centreY);
bsquared = b*b;
c = Math.sqrt(asquared + bsquared);
// …and comparing with radius
if(c < radius)
// hit inside, set color to gray and increment counter
inside = inside + 1;
// hit outside, set color to red and increment counter
outside = outside +1;
and then calculate an estimate for π
// update the estimate of pi
// ratio of area of a circle over area of a square is pi/4
// therefore, calc our approximation of pi as…
piestimate = 4*( inside/(inside+outside));
Placing the code in a loop to throw many darts refines the estimate on each iteration. Here’s what you get with 100,000 iterations:
Resulting in an estimate for π of 3.1492.
This approach is known as the Monte Carlo method. For reasons that should be obvious if you gamble.
I’d love to try this with real darts some day…