Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to Calculate Pi in Python
h
cjmatthy09 (14)

Hello, and welcome to this tutorial! We are going to be calculating Pi (3.1415...) using the Nilakantha series.
The series is quite basic.
First, you set the variable pi to 3.

pi = 3

Second, you define a variable called iterations. The higher the variable, the more precision. We will set it to 1000, but you can change this later.

pi = 3
precision = 1000 # change this later, or keep it!

Next,we will create a variable, bottom_number. This will be used for the following part.
Then, you add 4/bottom_number*(bottom_number+1)*(bottom_number+2). For example, you would do:
3 + (4/2*3*4) - (4/4*5*6)

(or

pi = 3
iterations=1000
bottom_number = 2
for i in range(iterations):
   if(i%2==0):
       pi += 4/(bottom_number*(bottom_number+1)*(bottom_number+2))
   else:
       pi -= 4/(bottom_number*(bottom_number+1)*(bottom_number+2))
   bottom_number += 2

We can implement this using the modulo operator with 2, and checking if it is 0. Make sure that bottom_number increments by 2, or else it would just be 4/234-4/234 and so on.

Also, the reason you use subtraction too is because the value would just converge roughly on 3.2xxxx and not Pi. We need to subtract or else the value will just add up infinitely.

Finally, every 100 iterations, so that we can see the convergence, we will add an if statement checking if this is the 100th, 200th, 300th, 400th, (and so on) digit.
We can do this the following way:

pi = 3
iterations=1000
bottom_number = 2
for i in range(iterations):
   if(i%2==0):
       pi += 4/(bottom_number*(bottom_number+1)*(bottom_number+2))
   else:
       pi -= 4/(bottom_number*(bottom_number+1)*(bottom_number+2))
   bottom_number += 2
   if(i%100==0):
       print(str(pi))

This will check if the variable i is divisible by 100 evenly, and if so, will print the current value of pi.

We are now done!
Try running the program:

3.1666666666666665
3.141592889142083
3.141592683919807
3.1415926626661848
3.141592657438003
3.1415926555659746
3.1415926547357
3.141592654312444
3.141592654074432
3.141592653930454

The 1st iteration is 3.1666666,
the 101st iteration is 3.141592xxxxxx (the x's are inaccuracies),
the 201st iteration is 3.1415926xxxxx,
and so on.

Thanks for reading, and have fun!
P.S: To continue this project, try coding your own algorithms for algorithms like Gauss-Legendre (hard), Gregory-Leibniz (easy), and so on!

Comments
hotnewtop
FloCal35 (502)

Hahaha, I know more digits of pi than the program (at this iteration)

cjmatthy09 (14)

@FloCal35 yeah, Nilakantha ain't too good. Try Gauss-Legendre with the decimal lib