calculate pi in python

There are several ways to calculate the value of pi in python. One popular method is the Leibniz formula:

main.py
import math

def calculate_pi(n_terms):
    numerator = 4.0
    denominator = 1.0
    operation = 1.0
    pi = 0.0

    for i in range(n_terms):
        pi += operation * (numerator / denominator)
        denominator += 2.0
        operation *= -1.0

    return pi

print(calculate_pi(100000))
294 chars
17 lines

This program will calculate pi using the Leibniz formula with 100,000 terms, resulting in a very accurate approximation. There are other algorithms, such as the Bailey-Borwein-Plouffe formula, that can be used to calculate pi to even greater precision.

gistlibby LogSnag