by gus_massa · 12y ago · 0 comments
> >>> int(math.exp(math.lgamma(41)))
> 815915283247882431423526575245034982027017846784L
> [...]
> Prelude> fac 40
> 815915283247897734345611269596115894272000000000
Another problem is that lgamma runs in constant time but it’s accurate only in a finite range. To extend the range the polynomial must have more terms, so the “accurate” version doesn’t run in constant time. And for enough precision, you must use the “long” version of the floating point numbers. The complete analysis is complex and I don’t have enough time to do it.
The recursive functions runs in linear time only for small numbers. It uses only integer arithmetic that is faster. But if the number are big enough you must use “long” integers, and the time is probably quadratic. So it’s not clear which version is better, neither for small numbers nor for big numbers and asymptotic behavior.
[1]: http://www.johndcook.com/blog/2012/07/14/log-gamma-differenc...
[2]: http://www.johndcook.com/blog/2010/08/16/how-to-compute-log-...
[3]: http://www.johndcook.com/blog/2008/04/24/how-to-calculate-bi...
In general, it's application-dependent. But often, in applications, the factorial enters multiplicatively, and they are in products with other stuff; the whole thing can easily underflow or overflow.
So what you often really want is the log of the factorial. (If someone gave you the exact integer factorial for free, the first thing you'd do is take its log.) That's why they implemented lgamma(). The error guarantees it gives are in the log domain, which is (often, not always) what you want, anyway.