# Easy Python Program to Calculate Leibniz Formula for π

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

for i in range(1, n, 2):
pi += 1/i
else:
pi -= 1/i
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
for i in range(1, n, 2):
pi = pi + (1/i if add else -1/i)