Learning in Stereo: Math + Python
Kirby Urner
urner at alumni.princeton.edu
Sun Apr 2 20:33:37 CEST 2000
> >>> pi(100)
> 3.04936163598
>
> >>> pi(10000)
> 3.14149716395
>
Of course you can push this slowly converging series even
further by rewriting f(n) to multiply with long integers:
>>> def f(n):
return 1.0/long(x)*x
>>> pi(100000)
3.14158310433
>>> pi(500000)
3.14159074373
Never use this as an efficient way to get PI!!
Here's a continued fraction method:
def pi(depth):
# use continued fraction of user-supplied depth to refine pi
n = 1.0
return 4.0 * 1.0/(1 + 1.0/pifract(n,depth))
def pifract(n,depth):
if n<depth:
return 2 + ((2*n+1)**2)/pifract(n+1,depth)
else: return 2.0
And here's another fast converger using every other
Fibonacci number:
def pifib(n):
# return approximation for pi using
# arctan(1) = 4 * SIGMA [ arctan(1.0/Fib(2i+1))]
sum = 0
for i in range(1,n+1):
sum = sum + math.atan(1.0/fibo(2*i+1))
return 4*sum
meaning you need and algorithm for the Fibonacci's, like:
fibcache = {} # thanks to Tim Peters
def fibo(n):
# return nth fibonacci number (recursive, cached)
if n == 0: return 0L
elif n == 1: return 1L
elif fibcache.has_key(n): return fibcache[n]
else:
result = fibo(n-1) + fibo(n-2)
fibcache[n] = result
return result
or
root5 = 5.0**0.5
gold = (1+root5)/2.0 # same as phi, named to not conflict with phi()
tau = 1/gold
def fibo(n): # thanks to David Zachmann
# return nth fibonacci number as a floating point
return (gold**n - (-tau)**n)/root5
Then of course there's always:
>>> import math
>>> math.pi
3.14159265359
:-D
Kirby
More information about the Python-list
mailing list