2016-12-05

PI4fun (Part 1)

Estimating $\pi$ for fun (Part 1: the basics)

The proposed project in this article is an example I tend to use in my Python introductory courses. The purpose is to calculate a dummy PI estimation based on a damn simple Monte Carlo algorithm.

It’s a simple and fun example that can be approached in a really direct and simple way, but that can be improved in many ways.

Let's start by imagining a blind darts player.

If we assume he performs completely random shots, the ratio between the darts inside a unit circle target and the corresponding unit square target will be equal to the ratio between the well known areas of the unit square and the unit circle:

\begin{equation*} \frac{D_c}{D_s} = \frac{\pi r^2}{(2r)^2} = \frac 1 4 \pi \to \pi = 4 \frac{D_c}{D_s} \end{equation*}

So, our approach will be to simulate random shots and cout how many of them hit inside the circle target and how many of them don't.

In Python, we can easily generate random numbers using the random module. With ´random.random()´ we can generate random numbers between 0 and 1:

In [1]:
import random
print random.random()
0.629933985288

With a couple of random numbers we can define a point in 2D space.

In [2]:
x = random.random()
y = random.random()
print (x,y)
(0.9696406993993923, 0.5337101093708417)

Now, we have to define a variable to store the shots hitting the target, start launching random shots and counting how many of then hit the target:

In [3]:
Inside = 0
Total = 100
for i in range(Total):
    x, y = random.random(), random.random()
    if (x**2+y**2) < 1: # Target!
        Inside += 1

Our $\pi$ approximation will be

\begin{equation*} \pi\approx 4\frac{I}{T} \end{equation*}
In [4]:
my_pi = 4.*Inside/Total
print "With %s random shots we've obtained an approximation of pi = %s" % (Total, my_pi)
With 100 random shots we've obtained an approximation of pi = 3.24

In next posts, we'll evolve this really simple example to make use of several interesting things such as structuring our code with functions and classes, applying several ways of optimization or drawing nice plots for illustrating the results.

Share on: