TheAlgorithms/Python · error · OverflowError

math range error

Error message

math range error

What it means

Raised by gamma_recursive in maths/gamma.py when num > 171.5. Gamma(171.625...) exceeds the maximum double-precision float (~1.8e308), so computing it would overflow; the code pre-empts this with OverflowError('math range error'), matching the behavior of math.gamma at the same threshold. The check runs before recursion begins.

Source

Thrown at maths/gamma.py:98

        ...
    ValueError: math domain error
    >>> gamma_recursive(-4)
    Traceback (most recent call last):
        ...
    ValueError: math domain error
    >>> gamma_recursive(172)
    Traceback (most recent call last):
        ...
    OverflowError: math range error
    >>> gamma_recursive(1.1)
    Traceback (most recent call last):
        ...
    NotImplementedError: num must be an integer or a half-integer
    """
    if num <= 0:
        raise ValueError("math domain error")
    if num > 171.5:
        raise OverflowError("math range error")
    elif num - int(num) not in (0, 0.5):
        raise NotImplementedError("num must be an integer or a half-integer")
    elif num == 0.5:
        return math.sqrt(math.pi)
    else:
        return 1.0 if num == 1 else (num - 1) * gamma_recursive(num - 1)


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    num = 1.0
    while num:
        num = float(input("Gamma of: "))
        print(f"gamma_iterative({num}) = {gamma_iterative(num)}")
        print(f"gamma_recursive({num}) = {gamma_recursive(num)}")
        print("\nEnter 0 to exit...")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Keep arguments at num <= 171.5; note that for factorial semantics n! = Gamma(n+1), so n must be <= 170.
  2. If you need Gamma of large arguments, work in log space: use math.lgamma(num) instead of gamma_recursive(num).
  3. For ratios of Gammas (common in statistics), rewrite using lgamma differences to avoid overflow entirely.

Example fix

// before
from maths.gamma import gamma_recursive
log_gamma = gamma_recursive(200)  # OverflowError

// after
import math
log_gamma = math.lgamma(200)  # works, returns ln(Gamma(200))
Defensive patterns

Strategy: fallback

Validate before calling

GAMMA_MAX = 171.5
if num > GAMMA_MAX:
    log_val = math.lgamma(num)  # work in log space instead

Try / catch

try:
    val = gamma_recursive(num)
except OverflowError:
    val = math.lgamma(num)  # or handle as 'too large for float'

Prevention

When it happens

Trigger: Calling gamma_recursive(172) or any num > 171.5, including large half-integers like 172.5. The 'if num > 171.5' branch raises immediately.

Common situations: Computing factorials of large numbers via Gamma (n! = Gamma(n+1), so factorials above ~170! overflow); combinatorics or statistics code that evaluates Gamma at unchecked large arguments; migrating from math.gamma and hitting the identical limit.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/e06842b459261d4d. Report an issue: GitHub.