Log-domain functions and inverse incomplete integrals
| Problem | Evaluate sums of exponentials, logistic functions and the normal CDF in the log domain without overflow or underflow; polygamma functions, the multivariate log-gamma function, Bernoulli and Euler numbers; invert the regularized incomplete gamma and beta functions |
| Devised by | Edmond Halley (1694), the cubically convergent iteration; Edwin Wilson and Margaret Hilferty (1931), the cube-root normal approximation; George Box and David Cox (1964), the power transform; Armido DiDonato and Alfred Morris (1986, 1992), the inversion of the incomplete gamma and beta functions |
| Accuracy | Agrees with SciPy to relative or better, except at the documented points below; Bernoulli numbers exact to rounding (SciPy’s are off by ) |
| Cost | logsumexp: two passes over the data. polygamma: one Hurwitz zeta evaluation. Inverses: a starting guess and a few Halley steps, each one incomplete gamma or beta evaluation |
| Read first | The gamma function, Incomplete gamma and beta functions, Zeta functions |
| API | logsumexp, softmax, expit, logit, log_ndtr, boxcox, polygamma, multigammaln, bernoulli, euler, gammaincinv, gammainccinv, betaincinv |
Overview
Probabilities and likelihoods span hundreds of orders of magnitude. A product of a thousand probabilities underflows, and a softmax of scores near 1000 overflows. The remedy is to work with logarithms, which needs a few functions that take and return logarithms without passing through the overflowing quantity:
logsumexp(a), the log of a sum of probabilities given as logs, andsoftmaxandlog_softmaxbuilt on it;logitandexpit, the log-odds and the logistic sigmoid, andlog_expit;log_ndtr, the log of the normal CDF, which is needed for likelihoods with censored data and in probit models.
The same entry collects other building blocks that SciPy has and the library lacked:
- the polygamma functions , the derivatives of the digamma function, which appear in the Fisher information of the gamma and beta distributions;
- the multivariate log-gamma function, which normalises the Wishart distribution;
- the Bernoulli and Euler numbers;
- the Box-Cox transform;
- the inverses of the incomplete gamma and beta functions. These are the quantile functions of the gamma, , beta, and Student distributions.
Where it is used
Probabilities and likelihoods are often too small to store as ordinary numbers.
- Machine learning and statistics. The log-sum-exp trick makes softmax, hidden Markov model forward-backward and mixture-model likelihoods computable without underflow.
- Communications. Log-likelihood ratios of decoders (LDPC, turbo) are combined in the log domain.
- Logistic regression. The sigmoid and log-sigmoid must be evaluated without overflow for large inputs.
- Extreme tails. Normal tail probabilities of 40 standard deviations are meaningful in reliability calculations and need log-domain evaluation.
History
Computing in the log domain is as old as logarithm tables. The “log-sum-exp trick” of factoring out the largest term is folklore in numerical analysis, and became indispensable with hidden Markov models (Baum, 1970s), where forward-backward probabilities underflow after a few hundred steps.
Inverting the incomplete gamma function is the classical problem of percentage points. Edwin Wilson and Margaret Hilferty (1931) observed that is nearly normal, which gives an accurate first guess. Armido DiDonato and Alfred Morris (1986) built a robust inversion on it, and Nico Temme (1992) gave uniform asymptotic expansions. Majumder and Bhattacharjee (1973) did the same for the incomplete beta function. Edmond Halley’s (1694) third-order iteration, ideal when the second derivative is cheap, completes both.
George Box and David Cox (1964) proposed the family of power transforms, choosing by maximum likelihood to make data nearly normal.
The idea
Factoring out the largest term
For ,
Every term on the right is at most 1, and one equals 1, so the sum lies in and its logarithm is accurate. The same
factorisation gives softmax, , and with signed weights the log of and its sign.
The logistic sigmoid overflows its intermediate for . expit uses
for negative instead. log_expit returns through ln_1p, which keeps the tiny value for large where
would round to 0.
The log of the normal CDF
. The naive fails at both ends (Figure 6.17):
- For , rounds toward 1 and the log toward 0, losing all relative accuracy. Instead, ,
computed with
ln_1pfrom the small . - For , underflows to 0. There the asymptotic expansion of Mills’ ratio gives Its terms decrease rapidly for .
Figure 6.17. The naive logarithm of the normal CDF compared with `log_ndtr`. In the middle it is accurate to an ulp. Above it loses digits steadily as approaches 1, and below the CDF underflows and the logarithm is .
Polygamma functions and friends
Differentiating times gives
a Hurwitz zeta function, which the library evaluates by Euler-Maclaurin summation. For negative non-integer , the recurrence moves the argument to positive values. Near the poles the shift terms are large and nearly cancel. At , is the difference of terms near , and 11 digits survive. A reflection formula for the derivatives of would avoid this.
The Bernoulli numbers follow from . Each one is a product of accurate factors, with no
recurrence to accumulate rounding. SciPy’s bernoulli uses a recurrence, and its is off by . The Euler numbers
use Dirichlet’s beta function the same way, , with
.
The multivariate gamma function is a product of ordinary gamma functions, so its logarithm is a sum of ln_gamma values.
Inverting the incomplete gamma and beta functions
To solve for , Newton’s method uses . The second derivative is just as cheap: . That gives Halley’s method, which converges cubically:
A good start leaves only a few steps. For the start is Wilson-Hilferty, , with the normal quantile of . For it is the small- behaviour . The incomplete beta function works the same way with , starting from a normal approximation for and from power laws at the ends of otherwise.
Accuracy depends on which tail the iteration targets. near 1 has only absolute accuracy, so for the inverse iterates on
with target . That subtraction is exact for . gammainccinv does the reverse. Before this rule,
gammainccinv(a, 0.999999) was off by ; with it, every case agrees with SciPy to .
Algorithm
log_ndtr(x): if , return ln_1p; if , return ; otherwise sum the
first 12 terms of the asymptotic series.
gammaincinv(a, p): if , solve instead; start from Wilson-Hilferty or the small- form; take Halley steps (halving if a step would make it
negative) until the step is below .
Implementation
/// `ln Σ exp(aᵢ)` without overflow (SciPy's `logsumexp`): with `m = max aᵢ`, the sum is
/// `m + ln Σ exp(aᵢ − m)`, whose terms are at most 1. Returns `−∞` for an empty slice or when
/// every term is `−∞`, and `+∞` if any term is `+∞`.
pub fn logsumexp(a: &[f64]) -> f64 {
let m = a.iter().copied().fold(f64::NEG_INFINITY, f64::max);
if !m.is_finite() {
return if a.iter().any(|v| v.is_nan()) { f64::NAN } else { m };
}
m + a.iter().map(|&v| (v - m).exp()).sum::<f64>().ln()
}
/// The logarithm of the standard normal CDF, `ln Φ(x)` (SciPy's `log_ndtr`), accurate in both
/// tails: for `x > −1` as `ln(1 − Φ(−x))` with `ln_1p`; for `−20 < x ≤ −1` from `erfc`, which is
/// accurate relative to its tiny value; below that from the asymptotic series
/// `ln Φ(x) = −x²/2 − ln(−x) − ½ ln 2π + ln(1 − 1/x² + 3/x⁴ − 15/x⁶ + …)`.
pub fn log_ndtr(x: f64) -> f64 {
if x.is_nan() {
return f64::NAN;
}
if x > -1.0 {
return (-0.5 * erfc(x * FRAC_1_SQRT_2)).ln_1p();
}
if x > -20.0 {
return (0.5 * erfc(-x * FRAC_1_SQRT_2)).ln();
}
let x2 = x * x;
let (mut term, mut sum) = (1.0, 1.0);
for k in 1..12 {
term *= -((2 * k - 1) as f64) / x2;
sum += term;
}
-0.5 * x2 - (-x).ln() - 0.5 * (2.0 * PI).ln() + sum.ln()
}
/// The polygamma function `ψ⁽ⁿ⁾(x)`, the `n`-th derivative of the digamma function (SciPy's
/// `polygamma`). For `n ≥ 1`, `ψ⁽ⁿ⁾(x) = (−1)ⁿ⁺¹ n! ζ(n + 1, x)` with the Hurwitz zeta function;
/// negative non-integer `x` is first shifted to positive values by
/// `ψ⁽ⁿ⁾(x) = ψ⁽ⁿ⁾(x + 1) + (−1)ⁿ⁺¹ n! / xⁿ⁺¹`. `NaN` at the poles `x = 0, −1, −2, …`.
pub fn polygamma(n: u32, x: f64) -> f64 {
if n == 0 {
return digamma(x);
}
if x.is_nan() || (x <= 0.0 && x == x.floor()) {
return f64::NAN;
}
let sign = if n % 2 == 1 { 1.0 } else { -1.0 };
let nf = factorial_f64(n as u64);
let (mut x, mut shift) = (x, 0.0);
while x <= 0.0 {
shift += sign * nf / x.powi(n as i32 + 1);
x += 1.0;
}
sign * nf * hurwitz_zeta(n as f64 + 1.0, x) + shift
}
/// The `x ≥ 0` with `P(a, x) = p` (SciPy's `gammaincinv`). The start is the Wilson-Hilferty
/// approximation for `a > 1` and the small-`x` series for `a ≤ 1`; then Halley steps
/// `x ← x − u / (1 − ½ u ((a−1)/x − 1))` with `u = (P − p)/P'` and `P' = x^{a−1} e^{−x} / Γ(a)`.
pub fn gammaincinv(a: f64, p: f64) -> f64 {
invert_gamma(a, p, false)
}
logsumexpreturns for an empty input or all terms, as SciPy does.boxcox(x, λ)is written as , which is continuous and accurate as .boxcox1pdoes the same for with small .bernoulliuses , as SciPy does.
In practice
The references come from SciPy 1.17.1 (book/generator/data/make_utilities_refs.py). The Bernoulli and Euler numbers are checked against exact rational
arithmetic instead, since SciPy’s own Bernoulli numbers are less accurate:
Table 6.13. Log-domain, polygamma and inverse functions against SciPy.
| computation (SciPy reference) | largest difference (relative) |
|---|---|
logsumexp (overflowing, underflowing and ordinary terms; signed weights) | 0 |
log_ndtr on −50, −49, …, 10 | 3e-15 |
expit and log_expit on ±800, ±40, ±5, … | 1e-16 |
logit from 10⁻¹² to 1 − 10⁻⁹ | 1e-16 |
polygamma, orders 1–4, x from 0.1 to 55.5 | 5e-16 |
polygamma, orders 1–4, x = −2.5 and −0.3 (cancellation in the shift; see the text) | 8e-12 |
multigammaln, dimensions 1, 2, 3, 10 | 1e-15 |
bernoulli, B₀ … B₃₀, against exact rationals (SciPy’s own error: 2e-12) | 8e-16 |
euler, E₀ … E₃₀, against exact integers (SciPy’s own error: 1e-15) | 2e-15 |
gammaincinv, a from 0.1 to 100, p from 10⁻¹⁰ to 1 − 10⁻⁶ | 5e-15 |
gammainccinv, the same grid | 1e-14 |
betaincinv, six (a, b) pairs, the same p | 4e-13 |
boxcox and boxcox1p | 0 |
The only differences above are the polygamma functions at negative arguments, explained above; betaincinv, limited by the
accuracy of the incomplete beta function itself; and the Box-Cox row in the statistics entry, where SciPy’s optimiser stops early.
Strengths
log_ndtris accurate to rounding from to , where the naive formula fails in both tails.- Inverse incomplete gamma and beta functions with cubic convergence, accurate in both tails.
- Bernoulli and Euler numbers accurate to rounding.
Weaknesses
polygammaloses digits next to the poles at negative arguments; SciPy uses a reflection formula there.- No complex arguments and no
wofz/Voigt function yet. - The starting guesses are simpler than DiDonato and Morris’s, so extreme parameters (for example ) can take more Halley steps.
Exercises
- Show that for a constant , and that softmax is unchanged by adding .
- Show that and that is its inverse.
- Derive the first terms of the asymptotic expansion of as by integrating by parts.
- Show that and .
- Derive Halley’s method from a second-order Taylor expansion, and the ratio for the incomplete gamma function.
- Why does the inverse iterate on the smaller of and ?
Hints and answers
- ; the softmax ratio cancels .
- . Solving gives .
- with ; write and integrate by parts repeatedly: , then take logs.
- . .
- Solve approximately by substituting the Newton step into the quadratic term. For , , so .
- Near the absolute error in is about , so the relative error in is , which can be huge; computed directly keeps full relative accuracy.
Further reading
- 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.
- N. M. Temme, “Asymptotic inversion of incomplete gamma functions”, Mathematics of Computation 58 (1992) 755–764.
- E. B. Wilson and M. M. Hilferty, “The distribution of chi-square”, Proceedings of the National Academy of Sciences 17 (1931) 684–688.
- G. E. P. Box and D. R. Cox, “An analysis of transformations”, Journal of the Royal Statistical Society B 26 (1964) 211–252.
- W. H. Press et al., Numerical Recipes, 3rd ed., Cambridge University Press, 2007, §6.2 (
invgammp,invbetai). - NIST Digital Library of Mathematical Functions, §5.15 (polygamma functions), §24 (Bernoulli and Euler numbers), §35.3 (multivariate gamma function).