[Tutor] Pi approximation

Roger Lea Scherer rls4jc at gmail.com
Wed Mar 28 15:09:07 EDT 2018


In one of my lessons I am asked to compare approximations for pi. I got
everything to work properly and my attempt is successful and matches
Python's approximation up to 15 digits to the right of the decimal, but I
suspect I can do this programmatically rather than the repetitious way I
did.

I tried "for i in range(10):"; then I tried "c += c" so it would be a sum.
Those attempts did not work. I tried math.fsum and though the documentation
says it is for iterables I could not get it to work as I desired. I
received an error that said TypeError: 'float' object is not iterable

I included all the code so I wouldn't neglect any you might need. Can you
help again?

Thank you.

# compare various approximations of pi
import math
import random

# simplest estimate
a = 22/7
print(a)

# next simplest
b = 355/113
print(b)

# from wikipedia:
# In 1910, the Indian mathematician Srinivasa Ramanujan found several
rapidly converging infinite series
c = (2*math.sqrt(2)/9801) * (((math.factorial(4*0))*(1103+26390*0)) /
((math.factorial(0)**4)*(396**(4*0))))
d = (2*math.sqrt(2)/9801) * (((math.factorial(4*1))*(1103+26390*1)) /
((math.factorial(1)**4)*(396**(4*1))))
e = (2*math.sqrt(2)/9801) * (((math.factorial(4*2))*(1103+26390*2)) /
((math.factorial(2)**4)*(396**(4*2))))
f = (2*math.sqrt(2)/9801) * (((math.factorial(4*3))*(1103+26390*3)) /
((math.factorial(3)**4)*(396**(4*3))))
g = (2*math.sqrt(2)/9801) * (((math.factorial(4*4))*(1103+26390*4)) /
((math.factorial(4)**4)*(396**(4*4))))
h = (2*math.sqrt(2)/9801) * (((math.factorial(4*5))*(1103+26390*5)) /
((math.factorial(5)**4)*(396**(4*5))))
i = (2*math.sqrt(2)/9801) * (((math.factorial(4*6))*(1103+26390*6)) /
((math.factorial(6)**4)*(396**(4*6))))
j = (2*math.sqrt(2)/9801) * (((math.factorial(4*7))*(1103+26390*7)) /
((math.factorial(7)**4)*(396**(4*7))))
k = (2*math.sqrt(2)/9801) * (((math.factorial(4*8))*(1103+26390*8)) /
((math.factorial(8)**4)*(396**(4*8))))
l = (2*math.sqrt(2)/9801) * (((math.factorial(4*9))*(1103+26390*9)) /
((math.factorial(9)**4)*(396**(4*9))))
m = c + d + e + f + g + h + i + j + k + l
print(1/m)

print(math.pi)


-- 
Roger Lea Scherer
623.255.7719


More information about the Tutor mailing list