# Monty Carlo Pi Approximation

Topic: Maths, Date: 03/06/2017

### What is PI?

To put it simply, PI is the ratio of a circles circumference to its diameter. We can find the irrational constant with the following calculation. Assuming we have a circle with a diameter $D$, we then measure the circumference $C$ of the circle. $\pi$ can then be calculated by $C/D$.

\begin{aligned} let \quad D &= 5, \\ C &= 15.72 \\ \therefore \quad \pi &\approx \frac{C}{D} = \frac{15.72}{5} = 3.144 \end{aligned}

Its not particularly accurate, but neither was the measurement I got for the circumference. Now we know how to calculate PI by 2 measurable quantities, it doesn't take much to see why the circumference of a circle is found by the formula $C = 2 \pi r = \pi D$. So if we had a circle with a diameter of 1, it's circumference would be equal to $\pi$.

As a side note, we can find the equation for the area of a circle by integrating the circumference equation (integration gives the area under a curve).

\begin{aligned} C &= \pi D = 2\pi r\\ A &= \int 2\pi r \, dr = \pi r^2 \end{aligned}

### Approximating PI

While the above method will give us a value for $\pi$, it's not exactly easy/possible to calculate via a computer, i.e., how do you measure the circumference of a circle draw on a screen automatically? The answer is... you don't. There are many other ways of calculating the decimal places of $\pi$. The Gauss-Legendre algorithm is a particularly interesting example of how to calculate $\pi$ (more can be found here). It's an iterative algorithm, whereby each pass through doubles the precision for the value of $\pi$. Since I write code in Erlang for a living, I have also provided an example solution for the algorithm here. It is worth noting, that running the algorithm past 3 iterations will just return the same number. This is because of the limit to floating point numbers in Erlang.

### Monty Carlo Method

For this post however, I am going to use a pretty basic Monty Carlo method. The idea is to place a unit circle inside a 1x1 square. We can then get a formula for $\pi$ based off the ratio of the circle's area and the square's area. $A_c$ is the area of the circle, $A_s$ is the area of the square.

\begin{aligned} A_c &= \pi r^2 \\ A_s &= (2r)^2 = 4r^2 \\ \frac{A_c}{A_s} &= \frac{\pi r^2}{4r^2} = \frac{\pi}{4} \end{aligned}

Given the above, we can see that $\pi$ can be calculated as $4 \times \frac{A_c}{A_s}$. The simulation below uses random sampling to produce a value for this ratio thus letting us approximate $\pi$ (albeit very badly).

0

1000

$\pi \approx$ 4 * Inside / All

Accuracy = | Math.PI - PI Approximation |