Python Program to Calculate Value of PI Using Leibniz Formula

The Leibniz formula is an infinite series method of calculating Pi. The formula is a very simple way of calculating Pi, however, it takes a large amount of iterations to produce a low precision value of Pi.

Leibniz formula:
π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
Or, π = 4 ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... )

In this python program we first read number of term to consider in series from user and then apply Leibniz formula to caluclate value of Pi.

This python program calculates value of Pi using Leibniz formula.

Python Source Code: Calculation of Pi using Leibniz Formula


# Calculation of PI using Leibniz formula

# Function to calcultae PI using Leibniz
def leibniz(n):
    t_sum = 0
    for i in range(n):
        term = (-1) ** i /(2*i+1)
        t_sum = t_sum + term
    
    return t_sum * 4

# Reading number of terms to be considered in Leibniz formula
terms = int(input("Enter number of terms: "))

# Function call
pi = leibniz(terms)

# Displaying result
print("Pi = ", pi)

Output

Enter number of terms: 100000
Pi =  3.1415826535897198
To get more accurate result use higher number of terms in series.