The Wayback Machine - https://web.archive.org/web/20220314220635/https://www.geeksforgeeks.org/calculate-pi-with-python/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Calculate Pi with Python

  • Last Updated : 19 May, 2021

Pi is an irrational number having non-recurring decimal values. We commonly know Pi=3.14 or Pi=22/7, but it is just an approximation for our ease. There are two methods to calculate the value of pi in python:

Method 1: Using Leibniz’s formula

The formula is –

X = 4 - 4/3 + 4/5 - 4/7 + 4/9 - ....

This series is never-ending, the more the terms this series contains, the closer the value of X converges to Pi value.

Approach:

  • Initialize k=1 // this variable will be used as the denominator of leibniz’s formula, it will be incremented by 2
  • Initialize sum=0 // sum will add all the elements of the series
  • Run a for loop from 0 to 1000000 //at this value, we get the most accurate value of Pi
  • Inside for loop, check if i%2==0 then do sum=sum+4/k
  • Else, do sum=sum-4/k
  • Increment k by 2, go to step 3

Below is the implementation:

Python3




# Initialize denominator
k = 1
 
# Initialize sum
s = 0
 
for i in range(1000000):
 
    # even index elements are positive
    if i % 2 == 0:
        s + = 4/k
    else:
 
        # odd index elements are negative
        s -= 4/k
 
    # denominator is odd
    k += 2
     
print(s)

Output:

3.1415916535897743

Method 2: Using acos() methods.

Approach:

  1. The value of Π is calculated using acos() function which returns a numeric value between [-Π, Π].
  2. Since using acos(0.0) will return the value for 2*Π. Therefore to get the value of Π:
 pi = round(2*acos(0.0));

Below is the implementation:

Python3




# Python3 program to calculate the
# value of pi up to 3 decimal places
from math import acos
 
# Function that prints the
# value of pi upto N
# decimal places
def printValueOfPi():
 
    # Find value of pi upto 3 places
    # using acos() function
    pi = round(2 * acos(0.0), 3)
 
    # Print value of pi upto
    # N decimal places
    print(pi)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Function that prints
    # the value of pi
    printValueOfPi()

Output:

3.142

Method 3: Using NumPy

In this method, we will use numpy.pi methods to calculate the pi value.

Python3




import numpy
 
print( numpy.pi )

 

 

Output:

 

3.141592653589793

 

Method 4: Using math module

 

Python has an inbuilt library named math we can simply import math and print the value of pi.

 

Python3




import math
 
print( math.pi )

Output:

3.141592653589793

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!