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,

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

$$ \frac{Area_{circle}}{Area_{square}} = \frac{\pi r^2}{4r^2} = \frac{\pi}{4} $$

$$ 4(\frac{Area_{circle}}{Area_{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 theorem to calculate its distance from the origin:

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

In other words, 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