# https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 """ 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 """ # 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)