[SciPy-user] calculating factorial
Stefan van der Walt
stefan at sun.ac.za
Sat Nov 19 05:13:34 EST 2005
I couldn't find "factorial", "combination", "permutation" etc. in
SciPy. Luckily, they're simple -- only problem is that my
implementation doesn't work :)
See the code listing below. I thought that the two methods for
calculating factorials should work equally well. I get an integer
overflow, no matter what typecode I use.
I realise that this behaviour might have changed with the new
scipy-base, so I'd appreciate if someone could test it and see.
from scipy import prod, arange, __version__
print "Scipy version", __version__
def factorial1(n):
f = 1
while (n >= 2):
f, n = f * n, n - 1
return f
def factorial2(n):
return prod(arange(2, n+1, typecode='u'))
print "\nFactorial method 1", factorial1(100)
print "\nFactorial method 2", factorial2(100)
Scipy version 0.3.3_309.4626
Factorial method 1 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Factorial method 2
Traceback (most recent call last):
File "./fact.py", line 17, in ?
print "\nFactorial method 2", factorial2(100)
File "./fact.py", line 14, in factorial2
return prod(arange(2, n+1, typecode='u'))
File "/home/stefan/lib/python/scipy_base/function_base.py", line 208, in prod
return _no_axis_is_all(multiply.reduce, m, axis)
File "/home/stefan/lib/python/scipy_base/function_base.py", line 164, in _no_axis_is_all
r = function(m, axis)
ArithmeticError: Integer overflow in multiply.
Stéfan
More information about the SciPy-User
mailing list