Incomplete gamma and beta functions and the error function
| Problem | Evaluate the regularised incomplete gamma functions and , the regularised incomplete beta function , the error function and its complement and inverse, and Dawson’s integral |
| Devised by | Incomplete gamma: Adrien-Marie Legendre and Friedrich Prym (19th century); incomplete beta: Karl Pearson’s tables (1934); the error function: named by James Glaisher (1871); Dawson’s integral: H. G. Dawson (1897); continued-fraction evaluation: William Lentz (1976), modified by Ian Thompson and Alan Barnett (1986); Dawson by George Rybicki (1989) |
| Accuracy | About relative for moderate parameters, for parameters in the hundreds |
| Cost | A series or continued fraction of to terms; Dawson’s integral, a sum of a few dozen exponentials |
| Read first | The gamma function and related functions |
| API | incomplete_gamma, incomplete_gamma_upper, incomplete_beta, error_function, erfc, erf_inv, dawson_integral |
Overview
Cutting the integrals that define the gamma and beta functions short gives the incomplete gamma and beta functions. Divided by the complete values, they are the cumulative distribution functions of the gamma and beta distributions, and through them of the Poisson, chi-square, binomial, Student’s and distributions (see statistical functions). The error function, the integral of a Gaussian, is a special case of the incomplete gamma function, and gives the probabilities of the normal distribution, the solution of the heat equation from a step, and the shape of a diffused interface.
The difficulty is that these functions are probabilities: values near 0 and near 1 both matter, and the complement must be computed directly, not by subtraction, when is close to 1.
Where it is used
Incomplete gamma and beta functions and the error function are cumulative distribution functions.
- Statistics. The normal CDF is an error function; the chi-square CDF is a regularised incomplete gamma function, and the t and F CDFs are incomplete beta functions, so every p-value of the statistics chapters is one of these.
- Communications. The bit error rate of a modulation in Gaussian noise is a Q-function, an error function in disguise.
- Heat conduction. The temperature in a semi-infinite solid after a sudden change at the surface is an error function.
- Reliability engineering. Poisson and gamma lifetime probabilities.
History
The incomplete gamma function was studied by Legendre and named and analysed by Friedrich Prym (1877) and others in the nineteenth century; Karl Pearson published extensive tables of both incomplete functions for statistics (1922, 1934). The error function arose with the normal distribution in the work of de Moivre, Laplace and Gauss; the name and the notation are due to James Glaisher (1871). H. G. Dawson tabulated the integral now named after him in 1897.
On computers, the standard methods became the power series for small arguments and continued fractions for large ones, evaluated by William Lentz’s algorithm (1976), made robust by Ian Thompson and Alan Barnett (1986). George Rybicki (1989) gave an elegant method for Dawson’s integral based on a sampling theorem.
The idea
The incomplete gamma function
The gamma function is an integral from 0 to . Stopping the integral at a finite point gives the incomplete gamma function, and dividing by so that the result runs from 0 to 1 gives the regularised forms
is the fraction of the integral accumulated up to , and is the remaining tail. These are the cumulative distribution functions of the gamma, chi-squared and Poisson distributions, which is why they matter. As a function of , rises from 0 to 1, most steeply near (where the integrand peaks), over a width of about :
Figure 6.2. The incomplete gamma function.
No single formula computes efficiently everywhere. Two expansions, each good on one side of the rise, cover the whole range.
Left of the rise: a series. For ,
Each term is the previous one multiplied by . When this ratio is below 1 from the start, so the terms decrease and the series converges quickly.
Right of the rise: a continued fraction. For the series would need many terms. There, Legendre’s continued fraction for the tail converges quickly instead:
A continued fraction is an expression of the form . Cutting it off after levels gives an ordinary fraction, its -th convergent, and the value of the continued fraction is the limit of the convergents. Continued fractions often converge in regions where power series converge slowly or not at all, which makes them the natural partner of a series.
Why each expansion is used where it is. There is a second reason for the split, besides speed. Left of the rise is the smaller of the pair, and right of it is. Each expansion computes the smaller quantity directly, to full relative accuracy, and the other follows by subtracting from 1, which loses nothing when the subtracted value is small. Doing it the other way round, computing a tiny tail as 1 minus a number very close to 1, would cancel most of its digits.
Evaluating a continued fraction. Written as above, a continued fraction seems to need evaluating from the bottom up, which requires deciding in advance how many levels to keep. The modified Lentz algorithm evaluates it from the top down instead. It keeps track of the ratios of successive convergents and multiplies the running value by one such ratio per level, stopping when the ratio is 1 to within rounding error.
The incomplete beta function
The same construction applied to the beta function gives the regularised incomplete beta function
which rises from 0 at to 1 at . It is the cumulative distribution function of the beta distribution, and through it of Student’s , the and the binomial distributions.
It has a continued fraction (derived from Gauss’s continued fraction for the hypergeometric function ) that converges rapidly for , the region below the mean of the beta distribution. Above that point the problem is reflected: swapping the roles of and in the integral gives the symmetry , and the right side is in the region of rapid convergence. The prefactor is computed from logarithms to avoid overflow for large parameters.
The error function
The error function and its complement are
is the area under the bell curve from 0 to , scaled to tend to 1; it gives the probability that a normally distributed measurement falls within a given distance of its mean. It is a special case of the incomplete gamma function. Substituting in the integral, so that , turns it into , and since ,
The library computes both through the incomplete gamma function.
Why provide as a separate function, when it is just ? Because of the upper tail. For beyond about 5.9, differs from 1 by less than the spacing of double-precision numbers, so it rounds to exactly 1 and evaluates to zero. The true value is small but not zero, and tail probabilities of that size matter in practice (error rates of communication links, for example). Computed directly, keeps full relative accuracy down to the underflow threshold near :
Figure 6.3. erfc and 1 − erf.
The inverse error function has no convenient series. It is found by solving for as a root-finding problem: start from Winitzki’s closed-form approximation and refine it by Halley’s method, a relative of Newton’s method that also uses the second derivative and converges cubically. Both and are elementary, so the extra derivative costs almost nothing.
Dawson’s integral
Dawson’s integral appears in the theory of plasma oscillations, in spectral line shapes (it is the imaginary part of the Faddeeva function on the real axis) and in heat conduction. Rybicki’s method starts from the sampling theorem, which gives the exact limit
and makes it practical by centring the sum on the even multiple of nearest , so that with and twenty terms each side the error is about . For the Taylor series is used.
Accuracy
Table 6.2. Accuracy of the incomplete gamma and beta functions and the error function.
| function | test points | median relative error | largest relative error | at arguments |
|---|---|---|---|---|
incomplete_gamma | 56 | 1e-16 | 4e-13 | (500, 100) |
incomplete_gamma_upper | 63 | 3e-16 | 2e-13 | (500, 600) |
incomplete_beta | 61 | 1e-16 | 5e-13 | (500, 500, 0.5) |
error_function | 28 | 0 | 1e-15 | (0.00000001) |
erfc | 24 | 2e-16 | 3e-14 | (25) |
erf_inv | 13 | 5e-16 | 2e-15 | (0.9) |
dawson_integral | 28 | 1e-16 | 4e-16 | (15.5) |
Algorithm
and .
- If : sum the series for , multiplying each term by to get the next, until a term is below times the sum. Then .
- Otherwise: evaluate the continued fraction for by the modified Lentz algorithm (below). Then .
In both cases the common factor is computed as to avoid overflow.
.
- Return 0 or 1 at the ends and .
- If : evaluate the continued fraction by the modified Lentz algorithm and multiply by the prefactor.
- Otherwise: compute by step 2 and return 1 minus it.
and . For , return and . For use the symmetries and .
The modified Lentz algorithm evaluates a continued fraction from the top down.
- Set , and .
- For : set and ; then ; then multiply by .
- Stop when is below a few .
and are ratios of successive numerators and of successive denominators of the convergents, so is the ratio of one convergent to the previous one. The modification is a guard: whenever , or (before inversion) is exactly zero it is replaced by a tiny number such as , which prevents a division by zero without affecting the result.
Implementation
The continued fraction for by the modified Lentz algorithm:
/// Continued fraction (modified Lentz) for the regularized upper function Q(a, x); `x >= a + 1`.
fn continued_fraction(a: f64, x: f64) -> f64 {
let mut b = x + 1.0 - a;
let mut c = 1.0 / FPMIN;
let mut d = 1.0 / b;
let mut h = d;
for i in 1..max_iter(a) {
let an = -(i as f64) * (i as f64 - a);
b += 2.0;
d = an * d + b;
if d.abs() < FPMIN {
d = FPMIN;
}
c = b + an / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
let del = d * c;
h *= del;
if (del - 1.0).abs() < EPS {
break;
}
}
(-x + a * x.ln() - ln_gamma(a)).exp() * h
}
The continued fraction for :
/// Continued fraction for the incomplete beta function (modified Lentz).
fn beta_cf(a: f64, b: f64, x: f64) -> f64 {
let qab = a + b;
let qap = a + 1.0;
let qam = a - 1.0;
let mut c = 1.0;
let mut d = 1.0 - qab * x / qap;
if d.abs() < FPMIN {
d = FPMIN;
}
d = 1.0 / d;
let mut h = d;
let max_iter = 1000 + (10.0 * a.max(b).sqrt()) as usize * 10;
for m in 1..=max_iter {
let m = m as f64;
let m2 = 2.0 * m;
let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1.0 + aa * d;
if d.abs() < FPMIN {
d = FPMIN;
}
c = 1.0 + aa / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
h *= d * c;
let aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1.0 + aa * d;
if d.abs() < FPMIN {
d = FPMIN;
}
c = 1.0 + aa / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
let del = d * c;
h *= del;
if (del - 1.0).abs() < EPS {
break;
}
}
h
}
- Arguments outside the domain (, , for the beta function) give
NaN. - The number of terms grows like near the transition : parameters of a few thousand are fine; for larger ones, uniform asymptotic expansions (Temme) would be faster.
In practice
//! Incomplete gamma and beta functions and the error function.
//!
//! Run with `cargo run -p lib_jsl_special_functions --example special_incomplete`.
use lib_jsl_special_functions::{dawson_integral, erf_inv, erfc, error_function, incomplete_beta, incomplete_gamma, incomplete_gamma_upper};
fn main() {
// The probability that a normal variable lies within one, two and three standard deviations.
for k in 1..=3 {
println!("P(|Z| < {k}) = {:.10}", error_function(k as f64 / 2f64.sqrt()));
}
// In the far tail, erfc keeps full relative accuracy where 1 − erf has none left.
println!("erfc(7) = {:e}, 1 − erf(7) = {:e}", erfc(7.0), 1.0 - error_function(7.0));
println!("erf⁻¹(0.95) = {:.12}", erf_inv(0.95));
// P(a, x) and Q(a, x): the chance that a Poisson process of rate 1 has its 3rd event by time 2.
println!("P(3, 2) = {:.12}, Q(3, 2) = {:.12}", incomplete_gamma(3.0, 2.0), incomplete_gamma_upper(3.0, 2.0));
// I_x(a, b): the chance that the median of 5 uniform samples is below 0.3.
println!("I_0.3(3, 3) = {:.12}", incomplete_beta(3.0, 3.0, 0.3));
println!("Dawson F(1) = {:.15}", dawson_integral(1.0));
}
Strengths
- Full relative accuracy in both tails, through the direct computation of the smaller of and .
- One continued-fraction engine serves the gamma, beta and error functions.
Weaknesses
- Slow for very large parameters, where asymptotic expansions are better.
- Real arguments only (no complex error function or Faddeeva function).
Exercises
- Show that and that for integer is the probability of at least events of a Poisson process of rate 1 by time .
- Show that by substituting .
- Derive the series for by repeated integration by parts of .
- Compute for and compare with the asymptotic formula . At what do they agree to six digits?
- Implement the modified Lentz algorithm for the continued fraction of and compare with
f64::tan.
Hints and answers
- . For integer , , which is the probability that a Poisson process of rate 1 has at least events by time .
- ; with this is .
- Integrate by parts: . Repeating gives .
- The first correction to the asymptotic formula is a relative , so even at the formula is off by about : six-digit agreement is not reached anywhere in (and the function underflows near ).
- Use with the modified Lentz algorithm (tiny-value protection for zero denominators); the continued fraction converges quickly for but needs more terms near .
Further reading
- W. J. Lentz, “Generating Bessel functions in Mie scattering calculations using continued fractions”, Applied Optics 15 (1976) 668–671.
- I. J. Thompson and A. R. Barnett, “Coulomb and Bessel functions of complex arguments and order”, Journal of Computational Physics 64 (1986) 490–509.
- A. R. DiDonato and A. H. Morris, “Computation of the incomplete gamma function ratios and their inverse”, ACM Transactions on Mathematical Software 12 (1986) 377–393.
- G. B. Rybicki, “Dawson’s integral and the sampling theorem”, Computers in Physics 3 (1989) 85–87.
- NIST Digital Library of Mathematical Functions, chapters 7 and 8, https://dlmf.nist.gov/7.