3 ms·
If you can live with floating point results: from math import gamma def factorial(x): return gamma(x+1) This has the advantage of working correctl
by tzs 15y ago
If you can live with floating point results:
from math import gamma
def factorial(x):
return gamma(x+1)
This has the advantage of working correctly for non-integer arguments.
- JoachimSchipper 15y agoTrue, but it requires 3.2+ and does not work correctly for large integers (floating-point runs out of precision long before Python's arbitrary-size integers become unusably large.) (Of course, this is a silly problem.)
- tzs 15y agoThe documentation says it requires 3.2+, but it is working in 2.7 on my Mac, both the 2.7 shipped by Apple and the 2.7 installed by MacPorts.
- tomku 15y agoThe factorial itself is only defined for non-negative integers. This may seem pedantic, but what you've defined there is actually Gauss's pi function, which has many interesting mathematical properties, but is not equivalent to the factorial because it has a larger domain. The results that it gives for non-integer arguments aren't any more "correct" than a factorial function throwing an exception, because they're both behaving appropriately for their defined domain. Edit: The math module has a factorial() function anyways, so it's a bit of a moot point. Use that :) Edit Edit: Thanks for the catch, I did mean non-negative integers instead of positive.
- JeanPierre 15y agoAs far as I know, 0! = 1, so I assume you meant non-negative integers instead of positive integers?
- chewxy 15y agoUm, the math module already has a factorial function which performs faster than the gamma function. Why use gamma?
- tzs 15y agoI didn't know about the factorial function.