Reference · Math

math.lgamma

signature
math.lgamma(num) -> float

What 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))
output
3.1780538303479458 3.17805383034794580.0 0.0 0.57236494292470015905.220423209181

Edge cases

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")))
output
1.2655121234846454 1.2655121234846454711.71472580229 158inf NaN

Errors

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.

this one fails
print(math.lgamma(0))
output
line 1: `math.lgamma`: math domain error (0)
this one fails
print(math.lgamma(-1))
output
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))
output
3.1780538303479458120 120

See also

math.gamma, math.factorial, math.log, math.comb

Thread
7Useful? Like it, or add to its thread below.

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