Reference · Math
math.lgamma
math.lgamma(num) -> floatWhat it does
The natural logarithm of the absolute value of the gamma function, as Python's
math.lgamma: math.lgamma(x) is log(|gamma(x)|), computed without forming
gamma(x) itself, so it works far past where math.gamma overflows.
math.lgamma(n + 1) is log(n!), the size of a factorial that no int or float could
hold.
Examples
print(math.lgamma(5), math.log(24))print(math.lgamma(1), math.lgamma(2), math.lgamma(0.5))print(math.lgamma(1000))3.1780538303479458 3.17805383034794580.0 0.0 0.57236494292470015905.220423209181Edge cases
math.lgamma(1)andmath.lgamma(2)are0.0, since0!and1!are1; elsewhere it agrees withmath.log(math.gamma(x))to a float's last digit or so.- The sign of gamma is dropped:
math.lgamma(-0.5)islog(3.545...), positive, thoughmath.gamma(-0.5)is negative. math.gamma(172)overflows a float butmath.lgamma(172)is about711.7; the number of digits ofn!ismath.lgamma(n + 1) / math.log(10), rounded up.- Infinity gives infinity, not an error; NaN stays NaN.
print(math.lgamma(-0.5), math.log(-math.gamma(-0.5)))print(math.lgamma(172), math.ceil(math.lgamma(101) / math.log(10)))print(math.lgamma(float("inf")), math.lgamma(float("nan")))1.2655121234846454 1.2655121234846454711.71472580229 158inf NaNErrors
Zero and the negative ints are the poles of gamma, and a runtime error here too,
math domain error, not an error value and not infinity, as Python's ValueError.
Minus infinity is the same. An argument so large that even the logarithm overflows a
float, math.lgamma(1e308), is a runtime error, math range error. An argument that
is not a number is a runtime error as well.
print(math.lgamma(0))line 1: `math.lgamma`: math domain error (0)print(math.lgamma(-1))line 1: `math.lgamma`: math domain error (-1)Chaining
In a pipeline the number comes first. log(n choose k) without any overflow:
print(5 | math.lgamma)let log_comb = (n, k) => math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)print(math.exp(log_comb(10, 3)) | round, math.comb(10, 3))3.1780538303479458120 120See also
math.gamma, math.factorial, math.log, math.comb
Thread 0 posts
On math.lgamma(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo