The Leibniz formula to calculate an approximation of the value of Ο is an infinite alternating series that adds and subtracts smaller and smaller terms of the form 1/x until it converges to the value of Ο/4. You can then multiply the result by 4 to obtain an approximation of Ο.
Here’s the simple formula that calculates Ο/4:
You can write a simple Python program that starts with pi = 0 and then iterates the following in a for loop, e.g., 10 million times:
- In the first, third, fifth, … iteration, add 1/i whereas i is a series going over all odd values i=1, 3, 5, …
- In the second, fourth, sixth, … iteration, subtract 1/i whereas i is a series going over all odd values i=1, 3, 5, …
Here’s how you can efficiently implement the Leibniz formula for Pi in Python code: π
def calculate_pi(): pi = 0 n = 10**7 add = True for i in range(1, n, 2): if add: pi += 1/i else: pi -= 1/i add = not add return pi*4 print(calculate_pi()) # 3.1415924535897797
Of course, you can get more precision by changing the value of n
to a possibly much higher value than 10 million.
If you care about conciseness, here’s a shorter but equally efficient way to calculate the Leibniz formula in Python:
def calculate_pi(n = 10**7): pi = 0 add = True for i in range(1, n, 2): pi = pi + (1/i if add else -1/i) add = not add return pi*4 print(calculate_pi()) # 3.1415924535897797
The main optimization in this code snippet compared to the previous one is that we used the ternary operator in Python. More here:
π Recommended Tutorial: The Ternary Operator in Python
Thanks for reading this tutorial—if you want to keep learning, feel free to join our free email academy. We have cheat sheets too! πΎ