create pi using a serie in python

We can use the following formula to calculate Pi:

Pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...)
47 chars
2 lines

Here's a Python code snippet that demonstrates how to use this formula to calculate Pi:

main.py
import math

def calculate_pi(num_terms):
    pi = 0
    sign = 1
    for i in range(1, num_terms * 2, 2):
        pi += sign * (1/i)
        sign *= -1
    return pi * 4

# Example usage
pi_estimate = calculate_pi(100000)
print(f"Pi is approximately: {pi_estimate}")
268 chars
14 lines

In this code, we define a function calculate_pi that takes a num_terms argument that specifies how many terms of the series to use in the calculation. Inside the function, we iterate over the odd integers up to num_terms * 2 and add/subtract their reciprocals from our running total pi. Finally, we multiply pi by 4 to get the estimate of Pi. By increasing the value of num_terms, we can get a more accurate estimate of Pi.

related categories

gistlibby LogSnag