In this Monte Carlo experiment, we generate random X and Y cordinates from -1 to 1. We then count the proportion of generated points that fall within a circle of radius 1 centred at (0, 0). The area of a circle of radius 1 is π, so the proportion of points that fall within satisfy X^{2} + Y^{2} ≤ 1 times the area of the square (which is 4) gives us an estimate of the area of the circle and hence the value of π.

Using this method, we take a hard problem — estimating the value of π — and solve it with a very simple algorithm that you can replicate, without much thinking, by throwing darts blindfolded. Normally to estimate a value of π, we'd have to draw and measure circles, or use outside knowledge of rules of thumb (such as approximating π to 3.14 or ^{22}⁄_{7}), or solve an infinite series. Of course, there are some limitations. In this case, since we are carrying out this simulation with JavaScript, floating point errors eventually thwart our efforts at achieving the ultimate prize of super precise approximations of π. But this general technique, called Monte Carlo Methods, of solving hard deterministic problems with easier probablistic solutions is really powerful and really cool.

The more sample points we take, the smaller our deviation from the true value of π. Here's the math:

Let sample i be represented by X_{i} that takes the value of 1 if point i falls within the circle, and 0 if it doesn't. Let M_{n} be the proportion of points that fall within the circle.

Expectation of X_{i}, E[X_{i}] = ^{π}⁄_{4}

Squared expectation of X_{i}, E[X_{i}^{2}] = ^{π}⁄_{4}

Variance of M_{n}, Var[M_{n}] = ^{Var[Xi]}⁄_{n} = ^{(π⁄4)(1 - π⁄4)}⁄_{n}

Thus as we can see, the expected value of our estimation is π, and the variance of our estimation from the true value decreases as the number of trials increases. None of this is really surprising mathematically, this is the equivalent of a binomial random variable being divided by its number of trials.

Blablabla, who cares about all the math, am I right? Here's a pretty circle, numbers flashing across the screen, and a pretty neat chart plotting our estimated value (powered by SmoothieCharts).

Our estimation:

Number of samples: 0

Number of sample points that fall within the circle: 0

Our estimation of π, 4 x proportion of samples within circle: ???