Lanczos approximation: Difference between revisions

Content deleted Content added
Simple implementation: Removed memoization note from code.
Line 50:
 
<source lang="python">
from cmath import sin, sqrt, pi, exp
def gamma(z):
epsilon = 0.0000001
def withinepsilon(x):
return abs(x) <= epsilon
 
p = [676.5203681218851
from cmath import sin,sqrt,pi,exp
,-1259.1392167224028
,771.32342877765313
,-176.61502916214059
,12.507343278686905
,-0.13857109526572012
,9.9843695780195716e-6, 1.5056327351493116e-7]
,1.5056327351493116e-7
]
 
EPSILON = 1e-07
p = [ 676.5203681218851, -1259.1392167224028, 771.32342877765313,
def drop_imag(z):
-176.61502916214059, 12.507343278686905, -0.13857109526572012,
if abs(z.imag) <= EPSILON:
9.9843695780195716e-6, 1.5056327351493116e-7]
returnz result= z.real
return resultz
def gamma(z):
z = complex(z)
 
# Reflection formula (edit: this use of reflection (thus the if-else structure) seems unnecessary and just adds more code to execute. it calls itself again, so it still needs to execute the same "for" loop yet has an extra calculation at the end)
if z.real < 0.5:
resulty = pi / (sin(pi*z) * gamma(1-z)) ### Reflection formula
else:
z -= 1
x = 0.99999999999980993
 
for (i, pval) in enumerate(p):
x += pval / (z+i+1)
 
t = z + len(p) - 0.5
resulty = sqrt(2*pi) * t**(z+0.5) * exp(-t) * x
return drop_imag(y)
 
"""
if withinepsilon(result.imag):
The above use of the reflection (thus the if-else structure) seems unnecessary
return result.real
and just adds more code to execute. It calls itself again, so it still needs
return result
to execute the same "for" loop yet has an extra calculation at the end)
"""
 
print gamma(1)
print gamma(5)
print gamma(0.5)
</source>