See http://mathworld.wolfram.com/BBPFormula.html
Not the most efficient Python but it works.
def x(n):
return (4.0/(8*n+1)-2.0/(8*n+4) - 1.0/(8*n+5) -1.0/(8*n+6))*((1.0/16)**n)
s = 0
for i in range(n):
s+=x(i)
return s
>>> pi(1)
3.1333333333333333
>>> pi(2)
3.1414224664224664
>>> pi(4)
3.1415924575674357
>>> pi(10)
3.1415926535897913
>>> pi(20)
3.141592653589793
>>> pi(40)
3.141592653589793
No comments:
Post a Comment