math.lgamma(x) returns the natural logarithm of the absolute value of math.gamma(x), added in Python 3.2.
Because lgamma() computes the logarithm directly without forming gamma(x) first, it handles gigantic values like math.lgamma(1000) effortlessly without raising OverflowError.
math.lgamma() is a function in Python's standard math module: import it with import math and call math.lgamma(...), or import the name directly with from math import lgamma.
Syntax
Import math and pass any non-pole real number.
python
import math
ln_abs_g = math.lgamma(x)
Call
What it does
math.lgamma(1)
Returns 0.0.
math.lgamma(2)
Returns 0.0.
math.lgamma(1000)
Returns approximately 5905.2204... (never overflows here).
math.lgamma(-1)
Raises ValueError: pole at negative integer.
Notice lgamma(x) returns the log of the absolute value|gamma(x)|, so even when gamma(x) is negative (e.g. x = -0.5), lgamma(-0.5) returns a real float.
Function signatures
python
math.lgamma(x, /)
# added in Python 3.2; returns float ln(|Gamma(x)|)
Parameters
Parameter
Description
x
Required positional real number (int or float), except 0 and negative integers.
Return Value
Return Value
Description
float
math.log(abs(math.gamma(x))); returns inf for both inf and -inf.
Python Examples
Example 1 — Compute Huge Log-Binomial Coefficients Without Overflow
Evaluate ln(comb(1000, 500)) via math.lgamma() where math.gamma(1001) would overflow.
No OverflowError at 1001. Direct gamma(1001) fails at 172, while lgamma(1001) succeeds easily.
Exact recovery on smaller cases. Exponentiating back for (10, 4) matches math.comb(10, 4) = 210.
Example 2 — Check lgamma(1) == 0.0 and Recover 6! = 720
Confirm zeros at 1 and 2 and exponentiate lgamma(7) back to 720.0.
python
import math
print(math.lgamma(1), math.lgamma(2))
recovered = math.exp(math.lgamma(7))
print(f"{recovered:.1f}", math.isclose(recovered, 720.0))
Output
0.0 0.0
720.0 True
How It Works
Logs of one are zero. Since both gamma(1) and gamma(2) equal 1.0, both log-gammas return 0.0.
Exponentiate to undo log. Calling math.exp() on lgamma(7) recovers 6! = 720.0.
Tolerance check confirms.math.isclose() matches the recovered float to 720.0.
Example 3 — Evaluate Negative Non-Integers and Catch Pole Errors
Observe real output for lgamma(-0.5) alongside ValueError at 0 and -1.
python
import math
print(f"lgamma(-0.5) = {math.lgamma(-0.5):.4f}")
print("lgamma(inf) =", math.lgamma(float("inf")))
for pole in [0, -1]:
try:
math.lgamma(pole)
except ValueError:
print(f"lgamma({pole}) raises ValueError")