Hacker News new | ask | show | jobs
by tzs 5214 days 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.
3 comments

The 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.

As far as I know, 0! = 1, so I assume you meant non-negative integers instead of positive integers?
True, 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.)

The 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.
Um, the math module already has a factorial function which performs faster than the gamma function. Why use gamma?
I didn't know about the factorial function.