In honor of Pi day (3/14/15 = 3.1415) I’ve decided to show people a simple program that will calculate the value of pi using Python.

Why Python?

It’s simple, I chose python because the syntax is easy to understand and the file name will be able to be pi.py (pronounced pie dot pie), evil laugh.

Leibniz Formula

To calculate Pi, we could just take the circle’s circumference and divide it by its diameter, but honestly who wants to take the easy way out?

No one.

So we are going to use the Leibniz Formula to calculate Pi.

It’s pretty simple actually, to calculate Pi we can use this formula:

Where n will be an infinity large and odd number, the more numbers you do the more accurate your calculation of pi will be, however, it will also take much longer!

And, if you care, here is this formula expressed in summation notation:

You can see this formula in action on Wolfram|Alpha.

This method is extremely slow compared to others, but it is easy to understand, that’s why we are using it.

The Python Program


# Pi Calculator
# By Michael Rouse
pi = 0
accuracy = 100000

for i in range(0, accuracy):
    pi += ((4.0 * (-1)**i) / (2*i + 1))

    print(pi)

for i in range(0, accuracy) will loop the indented code for all numbers between 0 and accuracy.

This for-loop is just the direct translation of the formula above.

Using this program I was able to calculate Pi to 3.14157 using accuracy of 100,000. (I know that the 7 doesn’t go there in Pi, but with more accuracy it will eventually change to a 9).

Running the Program

Go ahead and change the accuracy if you would like, just remember it will take longer with more accuracy.

Then run the program in whatever Python editor you like (you need a Python interpreter installed though) and then watch as Pi gets more and more accurate.

Happy π Day!