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! 👾

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.