Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The gamma function and related functions

ProblemEvaluate the gamma function , its logarithm and logarithmic derivative , the beta function , factorials and binomial coefficients
Devised byLeonhard Euler (1729), the gamma and beta functions; Adrien-Marie Legendre (1811), the notation ; James Stirling (1730), the asymptotic series; Cornelius Lanczos (1964), the approximation used here
AccuracyAbout relative for and , for ; factorials and binomial coefficients exact in integer arithmetic while they fit
CostA dozen arithmetic operations and one exp and powf
Read firstPreliminaries: floating-point arithmetic
APIgamma, ln_gamma, digamma, beta, ln_beta, factorial, factorial_f64, ln_factorial, binomial_coefficient, ln_binomial_coefficient

Overview

The gamma function extends the factorial from the integers to real (and complex) numbers, with . It is the most important special function: it normalises probability distributions (gamma, beta, chi-square, Student’s ), appears in the volume of a sphere in dimensions, in fractional derivatives and integrals, in the reflection formulas of almost every other special function, and in the functional equation of the zeta function. Its logarithm is needed whenever ratios of large factorials appear, and its logarithmic derivative, the digamma function, appears in statistics (maximum-likelihood estimates for gamma and beta distributions) and in sums of rational functions.

Where it is used

The gamma function extends the factorial and appears everywhere in probability.

  • Probability distributions. The gamma, beta, chi-square, Student’s t and many other densities are normalised with gamma functions.
  • Combinatorics. Binomial coefficients of large or non-integer arguments, and Stirling’s approximation.
  • Physics. Volumes of balls in dimensions, partition functions and scattering amplitudes.
  • Numerical lessons. The log-gamma function avoids overflow in everything that involves large factorials.

History

In 1729 Daniel Bernoulli and Christian Goldbach asked how to interpolate the factorial between the integers. Leonhard Euler answered in letters to Goldbach with an infinite product and, a few weeks later, the integral , equivalent to the modern definition below; he also introduced the beta integral. Adrien-Marie Legendre gave the function the letter and the shift by one that makes . James Stirling’s asymptotic formula (1730) for became the standard method of computing it. Harald Bohr and Johannes Mollerup (1922) proved that is the only log-convex function interpolating the factorial, which settles why it is the “right” extension.

For computers, Cornelius Lanczos (1964) found an approximation, a few terms of a rational series times an elementary factor, that is accurate to near machine precision for all positive arguments; with coefficients by Paul Godfrey and others it is the method used in most libraries, including this one.

The idea

The gamma function

Definition. For the gamma function is defined by Euler’s integral

Its connection with the factorial comes from integrating by parts, differentiating and integrating :

The bracket vanishes at both limits. Together with , the recurrence gives , , , and in general . The gamma function is the factorial, shifted by one and extended to non-integer arguments.

Negative arguments. The integral diverges for , but the recurrence, read backwards as , defines there: first on from the values on , then on , and so on. The division by produces a simple pole at , which the recurrence copies to .

Two identities. The reflection formula

relates the values at and , and so maps negative arguments to positive ones. Setting gives , so . The duplication formula is .

Figure 6.1. The gamma function.

Size. grows faster than any exponential and overflows double precision beyond . For that reason one usually computes its logarithm, , and exponentiates only at the end if at all. The reciprocal is better behaved: it is an entire function (analytic everywhere), with zeros where has poles.

Large arguments: Stirling’s series. For large ,

This series is asymptotic, a notion that recurs throughout this chapter. For a fixed its terms first decrease and then, eventually, grow without bound, so the infinite sum diverges. But if the sum is stopped while the terms are still decreasing, the error is about the size of the first omitted term, which for large is tiny. At the two correction terms shown are and , and the next is . An asymptotic series is very accurate for large and useless for small .

All positive arguments: the Lanczos approximation. Stirling’s series fails for small , and the recurrence needed to reach large loses a little accuracy at each step. Lanczos found a formula of Stirling’s type that is accurate for every . For a chosen constant ,

The factor in front is Stirling’s leading approximation with a shifted argument, and the bracket is a correction with coefficients that depend on and are computed once. With and nine coefficients the relative error is about for every , with no case analysis. The library uses it for , the reflection formula below that, and exact products for integers up to 171.

The digamma function

The digamma function is the logarithmic derivative of the gamma function, . It appears wherever a gamma function is differentiated, for example in maximum-likelihood fits of the gamma and beta distributions. Taking the logarithm of the recurrence and differentiating gives its own recurrence, , and its value at 1 is , where is the Euler-Mascheroni constant.

For large it has the asymptotic series , with Bernoulli numbers , obtained by differentiating Stirling’s series. The computation combines the two facts: use the recurrence to step the argument upward until it is large enough for the asymptotic series to be accurate, sum the series there, and subtract the terms accumulated on the way. Negative is handled by a reflection formula.

The beta function

The beta function is

the normalising constant of the beta distribution. It is computed through logarithms of gamma functions, to avoid overflow in the numerator and denominator.

Factorials and binomial coefficients

fits in a u64 up to and in an f64 up to ; the binomial coefficient is computed exactly in integers by the multiplicative formula , dividing at each step so that intermediate values stay small, with checked versions returning None on overflow. For large arguments, ln_factorial and ln_binomial_coefficient use .

Accuracy

Table 6.1. Accuracy of the gamma function and its relatives.

functiontest pointsmedian relative errorlargest relative errorat arguments
gamma276e-161e-13(170.5)
ln_gamma173e-166e-15(2.5)
digamma285e-168e-15(-0.5)
beta71e-157e-14(100, 200)
ln_beta79e-162e-15(0.01, 100)
factorial_f64507e-16(170)
ln_factorial306e-16(5)
ln_binomial_coefficient32e-163e-16(1000, 500)

The largest error of gamma, at , comes from the exponential in the Lanczos formula: a relative error in the argument of becomes an error in the result.

Algorithm

gamma(x) tests the argument against a sequence of cases, in this order, and uses the first that applies.

  1. is zero or a negative integer (a pole): return NaN.
  2. is a positive integer up to 171: return the exact product , accumulated by multiplication.
  3. : apply the reflection formula, , which calls the function again with an argument above .
  4. : the result exceeds the largest double; return .
  5. Otherwise: evaluate the Lanczos formula. The factor can overflow on its own although the final result is representable, so it is computed as the square of its square root, with the exponential factor applied in between.

ln_gamma(x) takes the logarithm of the Lanczos formula term by term, so that nothing overflows, and uses the reflection formula (in logarithmic form) for .

digamma(x): reflect if is negative; add and increase by 1 until it is large enough for the asymptotic series; then add the series.

beta(a, b): .

Every function costs a fixed, small number of operations.

Implementation

/// The gamma function Γ(x) for real `x`.
///
/// Uses a Lanczos approximation (relative error about 1e-15) with the reflection formula for
/// `x < 0.5`. Returns `NaN` at the poles (zero and the negative integers) and `+inf` on overflow
/// (`x > 171.62`). Positive integers are evaluated exactly as `(x-1)!`.
pub fn gamma(x: f64) -> f64 {
    if x.is_nan() {
        return f64::NAN;
    }
    if x == f64::INFINITY {
        return f64::INFINITY;
    }
    if x <= 0.0 && x == x.floor() {
        return f64::NAN;
    }
    if x == x.floor() && x <= 171.0 {
        let mut r = 1.0;
        let mut k = 2.0;
        while k < x {
            r *= k;
            k += 1.0;
        }
        return r;
    }
    if x < 0.5 {
        return PI / ((PI * x).sin() * gamma(1.0 - x));
    }
    if x > 171.7 {
        return f64::INFINITY;
    }
    let x = x - 1.0;
    let t = x + LANCZOS_G + 0.5;
    // Split the power to avoid premature overflow of t^(x+0.5).
    let half = t.powf(0.5 * (x + 0.5));
    (2.0 * PI).sqrt() * half * (-t).exp() * half * lanczos_sum(x)
}
  • factorial panics on overflow (use factorial_checked for Option); binomial_coefficient likewise, with binomial_coefficient_checked.
  • ln_gamma returns for negative non-integer .

In practice

//! The gamma function and its relatives.
//!
//! Run with `cargo run -p lib_jsl_special_functions --example special_gamma`.

use lib_jsl_special_functions::{beta, binomial_coefficient, digamma, factorial, gamma, ln_binomial_coefficient, ln_gamma};

fn main() {
    // Γ interpolates the factorial: Γ(n + 1) = n!, and Γ(½) = √π.
    println!("Γ(6) = {}, 5! = {}", gamma(6.0), factorial(5));
    println!("Γ(½)² = {:.15} (π = {:.15})", gamma(0.5).powi(2), std::f64::consts::PI);
    // Γ overflows past 171.6, but its logarithm does not.
    println!("Γ(200) = {}, ln Γ(200) = {:.6}", gamma(200.0), ln_gamma(200.0));
    // The volume of the unit ball in 10 dimensions, π^(n/2) / Γ(n/2 + 1).
    println!("volume of the unit 10-ball: {:.6}", std::f64::consts::PI.powi(5) / gamma(6.0));
    // B(a, b) = Γ(a) Γ(b) / Γ(a + b), and the digamma function ψ = Γ'/Γ (ψ(1) = −γ).
    println!("B(2.5, 1.5) = {:.12}, ψ(1) = {:.15}", beta(2.5, 1.5), digamma(1.0));
    // Binomial coefficients: exact in integers while they fit, or as logarithms.
    println!("C(50, 25) = {}, ln C(10000, 5000) = {:.6}", binomial_coefficient(50, 25), ln_binomial_coefficient(10_000, 5_000));
}

Strengths

  • Near machine precision for all arguments, with simple code.
  • Logarithmic versions avoid overflow in ratios of huge factorials.

Weaknesses

  • Real arguments only (no complex gamma).
  • Relative accuracy degrades slowly near the overflow limit and near the poles.

Exercises

  1. Prove by integration by parts, and compute from a Gaussian integral.
  2. Use Stirling’s series to estimate with two and three terms, and compare with ln_factorial(100).
  3. Show that the volume of the unit ball in is , and find the dimension in which it is largest.
  4. Verify the duplication formula numerically for several and estimate the rounding error.
  5. Compute as . How many correct digits does it have, and why?
Hints and answers
  1. . For put : .
  2. . With two terms beyond Stirling’s leading ones the error is of order for , and with three it is below .
  3. The volume is , which increases to a maximum at () and then decreases to zero.
  4. The duplication formula is ; compare both sides for several and expect relative differences of a few .
  5. , so the logarithm carries an absolute rounding error of about , and exponentiating turns that into a relative error of the same size: about 13 correct digits out of 16.

Further reading

  • P. J. Davis, “Leonhard Euler’s integral: a historical profile of the gamma function”, American Mathematical Monthly 66 (1959) 849–869.
  • C. Lanczos, “A precision approximation of the gamma function”, SIAM Journal on Numerical Analysis B1 (1964) 86–96.
  • NIST Digital Library of Mathematical Functions, chapter 5, https://dlmf.nist.gov/5.
  • E. Artin, The Gamma Function, Holt, Rinehart and Winston, 1964 (Dover reprint, 2015).