DEV Community

Cover image for Pi Approximation
Scott Gordon
Scott Gordon

Posted on

Pi Approximation

# pi_approximation.py
#   This program approximates the value of pi by summing the terms
#   of this series: 4/1-4/3+4/5-4/7+4/9-4/11+... The larger the 
#   amount of iterations, the less variance from Python's math.pi
# by: Scott Gordon

import math

print("***** Welcome to the PI Approximation Program *****")

n = int(input("How many terms would you like to sum? "))
sum = 0
sum2 = 0
numerator = 4
pi = math.pi

for i in range(1,n+1,4):
    sum -= numerator/i
for i in range(3,n+1,4):
    sum2 += numerator/i
total_sum = abs(sum + sum2)

print("The total approximation of pi based on",n, "terms of the series totaling", total_sum)
print("Compared to math.pi's results of", pi)
print("There is a difference of", total_sum-pi, "between the two.")

Enter fullscreen mode Exit fullscreen mode

Top comments (0)