SmexyyWeby

Scripting for Fun and Passion

Calculating Pi using Monte Carlo Simulation


Recently I have been intrigued by the uses of Monte Carlo simulation and a myriad of their uses in probabilistic modelling techniques especially in NLP and social network modelling. I wanted to learn more about the monte carlo process and understand what are some of its basic uses. An often cited example people gave me was that of calculating the value of $\pi$ defining it as 4 times the area of a circle inscribed in a unit length square.

The below figure shows the distribution of randomly generated points falling inside and outside the circle. Also the other figure shows how with the greater number of iterations the value of pi converges to the actual value of pi.

Monte Carlo Method for approximating the value of pi using ratio of area of circle inscribed in unit length square.

Monte Carlo Method for approximating the value of pi using ratio of area of circle inscribed in unit length square.

The intuition behind the simulation process is that if we randomly generate points confined inside a square circumscribing a circle then the probability of the points falling inside the circle will be directly proportional to the area of the circle. Since the circle is inscribed in the square hence its radius is 0.5 and hence the area will be $\pi/4$. This ratio is also approximately equal to the number points randomly generated inside the square which fall inside the circle to the total generated points. The approximation will should converge to the value equal to pi if we have very large number of points ideally tending to infinite points inside the square.

The below code does the simulation and generates the above figures:

The intriguing thing about this simulation is that using just 10000 points I am getting pretty good value of pi around 3.1392. This approximation however will change with each different run of the code as the randomly generated points change.

I am interested in learning more about such basic applications of monte carlo processes so that the understanding of the more complicated models is easier.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: