Estimating π with the Monte Carlo algorithm

Published on the

This page demonstrates the use of the Monte Carlo algorithm to estimate the value of the mathematical constant \(\pi\). The algorithm is simple, there is a circle of radius 1, inside a square of side length 2. The algorithm randomly places points inside the square. The area of the circle is \(\pi r^2\) i.e. \(\pi\) (since \(r = 1\)), and the area of the square is \(2^2\), i.e. 4. It follows that the proportion of points placed in the square that fall in the circle, \(k\), should be roughly equal to \(\frac{\pi}{4}\), i.e. \(k \approx \frac{\pi}{4}\), so \(\pi \approx 4k\). The more points the algorithm places, i.e. the more iterations the algorithm does, the more accurate the estimate of \(\pi\) is likely to be. Try 1000, 10,000 and 100,000 iterations to get a sense of this.

The code is written in JavaScript, and uses the HTML Canvas API to generate the graphic of the points on the circle. Then converts this to a data URI, which is injected into the source attribute of an image tag. This is better than putting the canvas element directly in the HTML, as this wouldn’t work well on small screen sizes. To avoid crashing your browser, the number of iterations is limited at 100,000. It must, of course, also be at least 1.