Integer multiplication overflow.
johnvert at my-deja.com
johnvert at my-deja.com
Sat Oct 7 22:49:11 EDT 2000
Hello,
I wrote the following simple recursive factorial function in python:
def fact(num):
if num < 2: 1
return num * fact(num - 1)
When I run it, I get the following:
>>> fact(3)
6
which is correct, but if I use something slightly larger:
>>> fact(15)
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in fact
File "<stdin>", line 3, in fact
File "<stdin>", line 3, in fact
OverflowError: integer multiplication
Why is that? If I compare this with the Scheme equivalent:
(define (fact num)
(if (< num 2)
1
(num * (fact (- num 1)))))
and run it with MzScheme, I can do:
> (fact 15)
1307674368000
> (fact 20)
2432902008176640000
and even,
> (fact 154)
30897696138473508879585646703632404659201907040888820477871589289865505687886666220300447285640952619071680544337494109264649994680187591361311072737951454695525676891035640863743200899694758450943586711068571022031011228320107310612480000000000000000000000000000000000000
So why does python choke (pun intended) on a slightly large
multiplication? I know it's not meant to be very numeric (although I
hear it's capable of a lot with the Numeric package,) but the factorial
of 15 is trivial.
Thanks a lot,
-- john
Les python newbie
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list