Iteration for Factorials

Lou Pecora pecora at anvil.nrl.navy.mil
Wed Oct 24 17:05:00 EDT 2007


In article <slrnfhvalj.67s.nick at irishsea.home.craig-wood.com>,
 Nick Craig-Wood <nick at craig-wood.com> wrote:

> Py-Fun <lorna.burns at gmail.com> wrote:
> >  I'm stuck trying to write a function that generates a factorial of a
> >  number using iteration and not recursion.  Any simple ideas would be
> >  appreciated.
> 
> Here is the math geek answer ;-)
> 
> import math
> 
> def factorial(i):
>     n = i + 1
>     return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n + 
>     1./288/n**2 - 139./51840/n**3)
> 
> Works for non integer factorials also...
> 
> See here for background
> 
>   http://mathworld.wolfram.com/StirlingsSeries.html


Well, that's Sterling's formula.  You do have to worry about 
convergence/accuracy.

How about (for intergers - simple-minded version):

def factorial(i):
   fact=1.0
   for n in xrange(i):
      fact=n*fact
   return fact

There might even be an array method that can be adapted to get the 
product.  Is there a product method? (analogous to a sum method)

Then you could use,

   arr=arange(i)+1
   fact=arr.product()  # or something like that

-- 
-- Lou Pecora



More information about the Python-list mailing list