[Tutor] factorial
Greg Chapman
greg@gregmchapman.info
Sun May 11 21:18:01 2003
>It gives the improbably wacky function:
>
> n! \approx
> \sqrt{2 \pi} n^{n+1/2} e^{-n}
>
>This equation is so strange that it must be true. *grin*
>
>
>Does anyone want to code it in Python and see how it compares to the exact
>factorial function?
Maybe I got the syntax wrong on Danny's approximation version, but the way I
did it it's way off.
Can anyone tell me if I got the syntax wrong or if the function actually
doesn't work well?
import math
def apFactorial(n): #this should be equivalent to Danny's
return ((math.sqrt(2 * math.pi)) * (n**(n+1/2)) * (math.exp(-n)))
def reFactorial(n): #this is Gerrit's recursive function from
his earlier post
if n<2: return n
else: return n*reFactorial(n-1)
def itFactorial(n): #and here's an iterative version I threw
together
i = n-1
while i:
n = n * i ; i -= 1
return n
if __name__ == '__main__':
print 'Approximate function:\t %d' % apFactorial(10)
print 'Recursive function:\t %d' % reFactorial(10)
print 'Iterative function:\t %d' % itFactorial(10)
The program output is:
Approximate function: 1138007
Recursive function: 3628800
Iterative function: 3628800