Iteration for Factorials
mensanator at aol.com
mensanator at aol.com
Wed Oct 24 17:32:48 EDT 2007
On Oct 24, 4:05 pm, Lou Pecora <pec... at anvil.nrl.navy.mil> wrote:
> In article <slrnfhvalj.67s.n... at irishsea.home.craig-wood.com>,
> Nick Craig-Wood <n... at craig-wood.com> wrote:
>
>
>
>
>
> > Py-Fun <lorna.bu... 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
Simple minded indeed.
>>> factorial(3)
0.0
>
> 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- Hide quoted text -
>
> - Show quoted text -
More information about the Python-list
mailing list