Estimating PI using Monte Carlo Simulations

Monte Carlo simulations are a class of computational algorithms that involve multiple computational trials driven by random sampling to approximate the optimal solution. Each trial is called a simulation, which is a random realization of the model for a given set of parameters. Because each simulation is powered by random numbers the results tend to be noisy, and is often necessary to run thousands of simulations in order to approximate the optimal solution.

One of the best examples to illustrate how Monte Carlo simulations work is estimating the value of \(\pi\). So how can we do that? First of all, we know that:

  • The area of the circle is \( A_{C} = \pi r^2 \).

  • The area of the square is \( A_{S} = (2r)^2 \).

Therefore, the ratio of the circle's area to the square's area is: $$ \frac{A_{C}}{A_{S}} = \frac{\pi r^2}{(2r)^2} = \frac{\pi r^2}{4 r^2} = \frac{\pi}{4} $$ and solving for \( \pi \) yields: $$ \pi = 4 \frac{A_{C}}{A_{S}} $$

This means that if we can find the ratio \(\frac{A_{C}}{A_{S}}\) on the right hand side of the equation, we can determine the value of \(\pi\). So how can we find the values for \(A_{C}\) and \(A_{S}\)? Here is where Monte Carlo simulations come into play. If we randomly choose \((x, y)\) points in the range \([-1, 1]\), we can calculate the distance of that point's location \((x^2 + y^2)\) from the origin. This would tell us if the point lies inside the circle, \(x^2 + y^2 < 1\), or outside the circle, \(x^2 + y^2 >= 1\).

The steps for this procedure can be summarized as follows:

  1. Generate \(N\) random points drawn from the interval \([-1, 1]\).
  2. The number of points generated, \(N\), will be the value of \(A_{S}\).
  3. The number of points that lie inside the circle, \(x^2 + y^2 < 1\), will be \(A_{C}\).
  4. Find the value \( \pi = 4 \frac{A_{C}}{A_{S}} \).


Here is a demo written in JavaScript for showing how a Monte Carlo simulation can estimate the value of \(\pi\). You can get the full source code of this tutorial on Github.

Your browser does not support HTML5 Canvas!
\( \pi \approx 4 \frac{A_{C}}{A_{S}} \)

comments powered by Disqus