A Monte Carlo simulation is a method of estimating events or quantities which are difficult or computationally infeasible to derive a closed-form solution to. The value of the mathematical constant Pi is a good example of this: although it is possible to calculate the exact value of Pi, a good estimate is easily demonstrated with just a few lines of code.

Monte Carlo simulations work when the input can be drawn from a random probability distribution, and the outcome can be derived deterministically from the input. In the case of calculating Pi, this can be modeled geometrically. The random distribution is all points within the square, and the outcome is whether a selected point lies within the circle inside of the square. We know that for a square circumscribed about a circle,

$ A_{circle} = \pi r ^ 2, A_{square} = (2r) ^ 2 = 4r ^ 2 $

$ { A_{circle} \over A_{square} } = { \pi r^2 \over 4r ^ 2 } = { \pi \over 4 } $

$ { 4 ({ A_{circle} \over A_{square} }) } = \pi $

If we notice that the probability that a randomly placed dot will fall within the circle is the same as the ratio of their areas (i.e. the circle takes up about 78% of the area of the square, so a random dot has about a 78% chance of landing inside the circle), then multiplying that probability by 4 gives Pi. By placing dots randomly, we play out that probability in real-time. As to whether a given dot lies within the circle, we simply use the Pythagorean theorum to calculate its distance from the origin:

$ \sqrt{ x^2 + y^2 } < 1 $

So all dots greater than 1 unit from the origin are outside the circle.

Below is a simulation of the derivation of the value of Pi. Click “start simulation” to see for yourself. Warning: this simulation may become slow once many dots are drawn on the screen.

Number of points: 0

% inside circle: 0

Approximate value of pi: 0

Next, I was interested in the way that this simulation would play out once the number of points became large. Intuitively, this should approach Pi, but doing so requires that the random numbers generated by browsers be evenly distributed.

Number of points: 0

Approximate value of pi: 0

% error: 0