16 Numerical Stability and Conditioning
16.1 Learning objectives
By the end of this chapter you should be able to:
- Describe IEEE 754 double-precision floating-point representation and identify the boundary cases (zero, subnormals, infinity, NaN) that affect statistical computation.
- Compute and interpret machine epsilon, and predict when ordinary arithmetic fails to satisfy the laws you remember from high-school algebra (associativity, distributivity).
- Recognize catastrophic cancellation when subtracting two nearly-equal floating-point numbers, and rewrite the affected expression to avoid it.
- Compute the condition number of a matrix or function and interpret it as ‘how many digits will I lose on this operation’.
- Distinguish forward error from backward error and explain why backward stability is the right objective for a numerical algorithm.
- Diagnose numerical fragility in R using
kappa(),.Machine,bench::mark(), and a small set of red-flag patterns. - Replace several classic statistical anti-patterns (computing variance via the textbook formula, computing \((X^T X)^{-1}\) by explicit inverse, computing \(\log \sum \exp\) naively) with their numerically stable counterparts.
16.2 Orientation
Computer arithmetic differs from real arithmetic. Every floating-point number is a real number rounded to one of a finite set, spaced unevenly across the real line. Every operation on floating-point numbers introduces a small relative error, on the order of \(10^{-16}\) for double precision. Most of the time we do not notice, because the errors are tiny and do not accumulate to anything visible. Unfortunately, some of the time we notice catastrophically. A regression that worked on simulated data fails on a real dataset. A likelihood that should be 0.999 returns 1.001. An MCMC chain produces NaN after a million iterations, and the cause is not apparent from the output.
The numerical-methods chapters of the first half, beginning with Chapter 5, taught the algorithms. In this chapter we shall consider when those algorithms break and how to tell. The material is foundational for every numerical chapter that follows. A working biostatistician who skips it tends to rediscover it one bug at a time over a career.
We begin with floating-point representation and the arithmetic laws it breaks, and then take up catastrophic cancellation. The condition number and the distinction between forward and backward stability come next. We close with a set of diagnostic patterns, stable rewrites of common formulas, and a worked example on the logistic likelihood.
16.3 The statistician’s contribution
An LLM can recite IEEE 754, the definition of a condition number, and the textbook anti-patterns, but it cannot recognize when our analysis is in numerical trouble. The judgments at the center of this chapter are diagnostic. That is, they concern what to suspect when something looks slightly off, and what to test for confirmation.
Suspect numerical fragility before suspecting bugs. Suppose a regression returns coefficients that contradict prior work, or a likelihood maximizes at a value that disagrees with a closed-form check. The first hypothesis should not be ‘I have a bug’. It should be ‘something here is ill-conditioned’. The diagnostic is fast. We compute the condition number, compute the gradient by finite differences and compare it to the analytic gradient, and perturb the input slightly while watching the output. If the output moves by more than the perturbation should produce, we look at the floating-point behavior of the algorithm on these data before looking for a coding error.
Statistical formulas in textbooks are not numerically stable formulas. The shortcut variance form \(\frac{1}{n-1}\bigl(\sum x_i^2 - n\bar x^2\bigr)\) is mathematically correct but numerically fragile. It subtracts two near-equal large numbers when \(\bar x\) is large relative to \(\sigma\), and the resulting catastrophic cancellation can produce a negative variance estimate. The centered-deviation form \(\frac{1}{n-1}\sum (x_i - \bar x)^2\) is numerically robust, and it is what R’s var() computes. Unfortunately, the textbook often presents the shortcut form without warning. The stable formulations exist in libraries, whereas the ones we type in from memory will be the textbook ones.
Match precision to need; do not over-promise. A floating-point answer with 16 digits of nominal precision may have only 10 actual digits after a moderately ill-conditioned operation. After a badly ill-conditioned one it may have only 4. A function that returns a 16-digit number does not flag whether all 16 are trustworthy, so the caller has to. Regression-coefficient point estimates reported to three digits with a 95% CI are honest. The same estimate reported to eight digits suggests a level of numerical certainty that the underlying computation cannot supply.
Test the boundary, not just the middle. Synthetic data drawn from \(N(0, 1)\) rarely exposes numerical problems. Real biomedical data have near-zero variances, near-collinear covariates, near-saturated probabilities, and observations that span many orders of magnitude. We test the center of the data distribution for correctness and the boundary for robustness. Code that passes only the first test works on the analyst’s laptop and fails on the next analyst’s harder dataset.
16.4 Floating-point arithmetic in one page
A double-precision floating-point number has 64 bits: 1 sign bit, 11 exponent bits, and 52 mantissa bits. In symbols, the number represented is
\[ (-1)^s \cdot (1 + m / 2^{52}) \cdot 2^{e - 1023} \]
where \(s\) is the sign bit, \(m\) the mantissa, and \(e\) the exponent. There are special cases for zero, subnormals (when \(e = 0\)), infinity (when \(e = 2047\) and \(m = 0\)), and NaN (when \(e = 2047\) and \(m \ne 0\)).
The relative gap between consecutive representable numbers is roughly \(2^{-52} \approx 2.22 \times 10^{-16}\). This quantity is machine epsilon, and R reports it together with the extreme representable values.
.Machine$double.eps
#> [1] 2.220446e-16
.Machine$double.xmax # largest finite double
#> [1] 1.797693e+308
.Machine$double.xmin # smallest positive normalized
#> [1] 2.225074e-308The largest integer exactly representable as a double is \(2^{53} = 9{,}007{,}199{,}254{,}740{,}992\). Beyond it, consecutive integers are no longer all representable.
2^53 == 2^53 + 1
#> [1] TRUEThis is one reason why patient identifiers and sequence reads are stored as integers or strings, not doubles.
16.4.1 The arithmetic laws change
Floating-point operations satisfy most of the laws of real arithmetic. There are, however, three important exceptions.
Addition is not associative. \((a + b) + c\) may differ from \(a + (b + c)\) because the rounding step between operations depends on operand magnitudes.
(1e100 + 1) - 1e100
#> [1] 0
1e100 + (1 - 1e100)
#> [1] 0
1 + 1e100 - 1e100
#> [1] 0 # the 1 is lostThe lost 1 is an instance of absorption (swamping). That is, a small number added to a much larger number is invisible at double precision, because the large number’s rounding swallows it.
Multiplication is not associative either, though the deviations are typically smaller and harder to construct.
The distributive law is approximate. \(a \cdot (b + c) \ne a \cdot b + a \cdot c\) in general, because the parenthesized sum rounds before the multiplication.
For algorithms whose correctness depends on the exact arithmetic laws, every operation is a place where a small error enters. The question for error analysis is whether those errors stay bounded or grow.
16.5 Catastrophic cancellation
When we subtract two nearly equal numbers, the leading significant digits agree and cancel. What remains is a small number whose precision is set by the trailing digits of the inputs. Unfortunately, those trailing digits are the rounding error, and so the result has lost most of its significant figures.
To illustrate, consider the canonical example, the textbook variance formula.
\[ \widehat{\sigma}^2 = \frac{1}{n-1} \sum_{i=1}^n (x_i - \bar x)^2 \]
This form is mathematically correct. Computed in two passes, it is also numerically stable whatever the size of \(\bar x\). An algebraically equivalent rearrangement, however, is
\[ \widehat{\sigma}^2 = \frac{1}{n-1} \left( \sum x_i^2 - n \bar x^2 \right) \]
which is what the textbook ‘shortcut formula’ computes. This form subtracts two large, nearly equal numbers (the sum of squares and \(n \bar x^2\)). It is catastrophically unstable for data whose mean is large relative to their standard deviation. The following example, with a mean of about \(10^9\) and a standard deviation of about 1, makes the point.
x <- 1e9 + rnorm(1000, sd = 1) # mean ~1e9, sd ~1
# stable: two-pass
mean_x <- mean(x)
var_stable <- sum((x - mean_x)^2) / (length(x) - 1)
var_stable
#> [1] 1.014 # close to true variance ~1
# unstable: shortcut formula
var_naive <- (sum(x^2) - length(x) * mean_x^2) / (length(x) - 1)
var_naive
#> [1] -23.5 # negative; clearly wrong
# what R's var() actually does (two-pass centered-deviation, stable)
var(x)
#> [1] 1.014The shortcut formula gives a negative variance estimate. We note that the naive code does not crash. Instead it produces a plausible-looking number that is wrong by orders of magnitude.
There are three cures.
- Two-pass. Compute the mean first, and then sum the squared deviations. This doubles the passes over the data but is numerically robust. It is what R’s
var()andsd()use internally (the C source calls a centered-deviation sum after a separate mean pass). - Welford’s online algorithm. This single-pass method updates a running mean and sum of squares in a numerically stable way. It is the standard choice for streaming data, where two passes are not available.
- Center the data first. Subtract any reasonable approximation of the mean from every observation, and compute on the centered data. This is useful when we need to express the variance through a formula that the shortcut form would otherwise tempt us into.
In a regression setting, the same issue appears when \(X\) has columns of very different magnitudes, so that \(X^T X\) becomes numerically near-singular. The cure is to center and scale the columns before forming \(X^T X\). Alternatively, we may work directly with the QR decomposition of \(X\), which never forms \(X^T X\).
16.6 The condition number
The condition number of a numerical problem measures how much the solution changes when the input is perturbed. For solving \(A \mathbf{x} = \mathbf{b}\) it is
\[ \kappa(A) = \|A\| \cdot \|A^{-1}\| \]
(in any consistent norm). For the 2-norm, \(\kappa_2(A)\) is the ratio of the largest to the smallest singular value.
The interpretation is as follows. A relative perturbation of size \(\epsilon\) in the right-hand side \(\mathbf{b}\) produces a relative perturbation of size up to \(\kappa(A) \epsilon\) in the solution \(\mathbf{x}\). With double-precision input, a matrix with \(\kappa(A) \approx 10^{12}\) therefore permits roughly \(\log_{10}(10^{16} / 10^{12}) = 4\) digits of meaningful precision in the answer.
In R we compute it with kappa().
A <- matrix(c(1, 1, 1, 1.0001), 2, 2)
kappa(A, exact = TRUE)
#> [1] 40004
log10(kappa(A, exact = TRUE))
#> [1] 4.602 # about 11 digits of precision out of 16A few rules of thumb merit memorizing.
- \(\kappa(A) \le 100\): well-conditioned. Most or all 16 digits are meaningful.
- \(\kappa(A) \approx 10^6\): moderately ill-conditioned. About 10 digits meaningful.
- \(\kappa(A) \approx 10^{12}\): severely ill-conditioned. About 4 digits meaningful.
- \(\kappa(A) \ge 10^{16}\): numerically singular at double precision. The computed solution is dominated by rounding error.
In biostatistical work, large condition numbers have three common sources.
- Collinear or near-collinear covariates. Two columns of \(X\) that are nearly proportional inflate \(\kappa(X^T X)\) to \(\kappa(X)^2\), which is the squared condition number.
- Wildly different scales. A design matrix with one column in millions (genome positions) and another in tenths (proportions) has a \(\kappa(X^T X)\) much larger than necessary. We center and scale before fitting.
- Vandermonde-like structure. Polynomial regression with degree above 5 or so produces matrices whose condition numbers explode. Orthogonal polynomials are the remedy (
poly()instead ofcbind(x, x^2, x^3, ...)).
For the regression problem \(X^T X \boldsymbol\beta = X^T y\), the condition number of the linear system is \(\kappa(X^T X) = \kappa(X)^2\). Working with the QR decomposition of \(X\) avoids forming \(X^T X\) at all. It keeps the conditioning at \(\kappa(X)\), not \(\kappa(X)^2\), and this is why lm() uses QR.
16.7 Forward and backward stability
A numerical algorithm computes \(\hat y = f^*(x)\) rather than the exact \(y = f(x)\). There are two ways to think about the error.
Forward error. The forward error is \(\|\hat y - y\|\), the distance between the computed and exact answers. It is what we would naturally want to bound. However, it depends jointly on the algorithm and on the conditioning of the problem.
Backward error. The backward error is the smallest perturbation \(\Delta x\) such that \(\hat y = f(x + \Delta x)\). That is, the algorithm produces the exact answer to a slightly different problem.
Backward error analysis, developed by Wilkinson in the 1960s, is the dominant analytical framework in modern numerical analysis. An algorithm is backward stable if \(\|\Delta x\| \le C \cdot \epsilon_\text{mach}\) for some modest constant \(C\). The forward error is then bounded by \(\kappa(f) \cdot \|\Delta x\|\), and so
\[ \frac{\|\hat y - y\|}{\|y\|} \lesssim \kappa(f) \cdot \epsilon_\text{mach} \]
This factorization separates algorithm quality (whether the algorithm is backward stable) from problem difficulty (the condition number). A backward stable algorithm produces forward errors as small as the problem permits. Conversely, no algorithm operating in finite precision can solve an ill-conditioned problem accurately.
The practical consequence is that, when we observe a large forward error, we ask which factor is responsible. If the condition number is huge, no algorithm can save us. We may accept the limited precision, regularize the problem, or use higher-precision arithmetic. If the condition number is small but the answer is still wrong, the algorithm is unstable and should be replaced.
16.8 Diagnostic patterns
A small set of patterns surfaces most numerical fragility in statistical code. We present four of them.
Pattern 1: compare to a closed-form benchmark. When a numerical answer disagrees with a closed-form check, the question is the size of the disagreement. At the rounding level it is acceptable. Many orders of magnitude larger, it indicates a bug or an instability.
# closed form for OLS on synthetic data
set.seed(1)
n <- 100; p <- 3
X <- cbind(1, matrix(rnorm(n * p), n, p))
beta_true <- c(2, 1, -0.5, 0.3)
y <- X %*% beta_true + rnorm(n)
# fit two ways; compare
beta_lm <- coef(lm(y ~ X[, -1]))
beta_qr <- qr.coef(qr(X), y)
max(abs(beta_lm - beta_qr))
#> [1] 1.776e-15 # at machine precision; agreementIf this agreement breaks down (to \(10^{-6}\) or larger), we investigate.
Pattern 2: perturb and watch. Add a small amount of noise to the input and recompute. The output should move by an amount proportional to the noise.
A <- matrix(c(1, 1, 1, 1.0001), 2, 2)
b <- c(2, 2.0001)
x_orig <- solve(A, b)
x_pert <- solve(A, b + c(0, 1e-10)) # tiny perturbation
max(abs(x_pert - x_orig))
#> [1] 1e-06 # output moves 10000x more than inputThe output moved \(10^4\) times more than the input. This is the condition number \((\approx 4 \times 10^4)\) at work. In research code we would automate this check on real data. Any operation whose output sensitivity is larger than expected would then be flagged.
Pattern 3: compute the gradient two ways and compare. An analytic gradient should be compared to a finite-difference gradient. Disagreement above \(10^{-6}\) or so indicates a bug, typically in the analytic version.
library(numDeriv)
f <- function(x) sum((x - 0.3)^2)
gf <- function(x) 2 * (x - 0.3)
x <- runif(5)
max(abs(gf(x) - grad(f, x)))
#> [1] 4.5e-11 # agreement at numerical-derivative precisionPattern 4: monitor the magnitude of intermediate quantities. When debugging an MCMC chain that produces NaN, we log every intermediate variance estimate, every covariance matrix’s condition number, and every likelihood contribution. The first quantity to overflow, underflow, or become singular is the immediate cause. The algorithmic root cause is usually one or two steps upstream.
16.9 Stable rewrites of unstable formulas
We now present three classic anti-patterns and their stable replacements.
Antipattern: \(\log \sum_i \exp(z_i)\) computed naively.
z <- c(1000, 1001)
log(sum(exp(z)))
#> [1] Inf # overflowThe fix is the log-sum-exp trick: factor out the maximum before the exponential.
logsumexp <- function(z) {
M <- max(z)
M + log(sum(exp(z - M)))
}
logsumexp(z)
#> [1] 1001.313This computation appears whenever we normalize a probability across many categories, as in softmax, mixture-model responsibilities, and log-likelihood contributions in models with many random effects. R’s matrixStats::logSumExp provides a robust implementation.
Antipattern: \(1 - \exp(z)\) for \(z\) near zero.
z <- 1e-10
1 - exp(z)
#> [1] -1e-10 # severe cancellationR provides expm1(z), which computes \(\exp(z) - 1\) accurately for small \(z\).
-expm1(z)
#> [1] -1e-10 # but with full precisionLikewise, log1p(z) computes \(\log(1 + z)\) accurately for small \(z\). These functions appear in CDFs for distributions that are close to 1 in the upper tail, in the logistic-regression log-likelihood for predictions near 0 or 1, and in survival analysis.
Antipattern: solving \(X^T X \boldsymbol\beta = X^T y\) via explicit inverse.
beta <- solve(t(X) %*% X) %*% t(X) %*% y # bad
beta <- solve(crossprod(X), crossprod(X, y)) # better
beta <- qr.coef(qr(X), y) # bestThe first form computes \(X^T X\) and inverts it explicitly. Forming \(X^T X\) inflates the condition number from \(\kappa(X)\) to \(\kappa(X)^2\), and the explicit inverse is both numerically worse and computationally wasteful. The QR-based form avoids forming \(X^T X\) entirely and preserves the original conditioning.
16.10 Worked example: a numerically robust logistic likelihood
To illustrate the ideas of this chapter on a realistic problem, consider the logistic-regression log-likelihood,
\[ \ell(\boldsymbol\beta) = \sum_i \left[ y_i \mathbf{x}_i^T \boldsymbol\beta - \log(1 + \exp(\mathbf{x}_i^T \boldsymbol\beta)) \right]. \]
Here \(\mathbf{x}_i\) is the covariate vector and \(y_i\) the binary response for observation \(i\). The naive computation of log(1 + exp(eta)) overflows when \(\eta\) is large positive. It underflows (returning \(\log 1 = 0\)) when \(\eta\) is large negative. The robust form uses log1p and a max trick.
loglik_logistic <- function(beta, X, y) {
eta <- as.numeric(X %*% beta)
# log(1 + exp(eta)) without overflow:
# for eta >= 0: eta + log(1 + exp(-eta))
# for eta < 0: log(1 + exp(eta))
# combined via max trick:
m <- pmax(eta, 0)
log1pe <- m + log1p(exp(-abs(eta)))
sum(y * eta - log1pe)
}We compare it with the naive form on a difficult input.
set.seed(1)
n <- 200
X <- cbind(1, scale(matrix(rnorm(n * 3), n, 3)))
beta <- c(0.5, 50, -50, 0) # extreme coefs to force trouble
y <- rbinom(n, 1, plogis(X %*% beta))
beta_test <- c(0, 60, -60, 0)
naive <- function(beta, X, y) {
eta <- as.numeric(X %*% beta)
sum(y * eta - log(1 + exp(eta)))
}
naive(beta_test, X, y)
#> [1] -Inf # log(exp(huge)) overflows
loglik_logistic(beta_test, X, y)
#> [1] -2754.3 # finite and meaningfulThe naive version returns -Inf. An optimizer treats this value as a barrier, and the optimization stops. The robust version, on the other hand, returns a finite value that the optimizer can work with.
16.11 Collaborating with an LLM on numerical stability
LLMs are reasonably good at recalling the textbook anti-patterns in this chapter and at writing the stable replacements. They are less reliable at identifying which of our specific formulas are unstable. That task requires working through the magnitudes that arise in the data at hand.
Prompt 1: review for instability. Paste a short function (a likelihood, a moment computation, a closed-form estimator) and ask: ‘identify any numerical-stability risks in this code, and propose stable rewrites where relevant.’
What to watch for. The LLM should flag subtractions of nearly equal quantities, naive log(1 + exp(x)) and log(sum(exp(x))), explicit matrix inverses, computations of variance via the shortcut formula, and the accumulation of many small additions to a large running total. If it flags none of these on a function that contains one, we would push back. If it flags others as well, we evaluate each.
Verification. Construct an extreme input (mean far from zero, near-collinear design, near-zero variance) and run both versions. The stable rewrite should produce a finite, sensible number. The unstable version should produce overflow, underflow, NaN, or wildly wrong values.
Prompt 2: explain a numerical bug. Paste the failing output and the surrounding code, and ask: ‘this returns NaN on a small subset of inputs. Trace the failure: what is the first quantity that becomes NaN, and why?’
What to watch for. The LLM is good at the standard failure cascades. Examples are zero variance leading to division by zero and then NaN, or a covariance matrix with a tiny negative eigenvalue from rounding, which causes the Cholesky factorization to fail. It is less reliable for domain-specific cascades, such as a hierarchical-prior scale collapsing to zero in a Bayesian model. If the answer sounds vague, we ask the LLM to state the failure in terms of specific quantities and where they were last finite.
Verification. Add stopifnot() or cat(...) checkpoints at each stage of the computation. The first checkpoint that triggers identifies the precise failure point, which we then compare to what the LLM predicted.
Prompt 3: produce a numerically robust implementation. Describe the mathematical formula and the input ranges, and ask: ‘implement this in R, prioritizing numerical robustness over brevity. Use log1p, expm1, logSumExp, crossprod, qr.coef, and similar where applicable. Comment on each numerical-stability decision in the code.’
What to watch for. The LLM should produce code with an explicit stability rationale in its comments. If the comments are absent or generic, the implementation may be a straight transcription of the formula, written without thought about magnitudes. If the code matches a textbook anti-pattern, we ask for a specific rewrite.
Verification. Test on three input regimes: typical (centered near zero, modest variance), extreme (mean far from zero), and pathological (near-collinear design or saturated probabilities). The robust implementation should work on all three, whereas the textbook implementation will fail on the second or third.
16.12 Principle in use
Three habits define defensible numerical practice:
- Compute condition numbers. Whenever we solve a linear system, fit a regression, or invert a matrix, we compute and look at the condition number. It takes one line of code, and it surfaces the numerical risk before it becomes a wrong answer.
- Use stable rewrites by default. These include
log1p,expm1,logSumExp,crossprod,qr.coeffor OLS, and two-pass variance. The stable form should be the habit. The unstable form is warranted only when its safety has been specifically verified. - Test the boundary. Synthetic data centered near zero rarely exposes problems. We run on data with means far from zero, near-collinear covariates, and probabilities near 0 or 1, since these are the regimes that production data often occupy.
16.13 Exercises
- Compute the variance of
1e9 + rnorm(1e5)two ways: the shortcut formula andvar(). Document the difference. Now repeat with1e15 + rnorm(1e5). At what magnitude of mean does the shortcut formula become useless? - Construct a \(5 \times 5\) Hilbert matrix \(H_{ij} = 1/(i + j - 1)\). Compute its condition number. Solve \(H \mathbf{x} = \mathbf{b}\) for \(\mathbf{b}\) chosen so the exact answer is \(\mathbf{x} = (1, 1, 1, 1, 1)\). Report the relative error. Repeat for \(n = 10\) and \(n = 12\).
- Implement a numerically robust softmax function: \(\sigma_i(\mathbf{z}) = \exp(z_i) / \sum_j \exp(z_j)\). Verify on inputs containing values larger than 700, where naive softmax overflows.
- The logistic CDF \(F(z) = (1 + e^{-z})^{-1}\) has a naive implementation that rounds to exactly 1 for large positive \(z\) and underflows to 0 for large negative \(z\). Taking the log then returns 0 and
-Inf, respectively, and the tail information is lost. Implementlog(plogis(z))accurately for both tails. Hint: this is what R’splogis(z, log.p = TRUE)does; verify your implementation against it. - Take a regression of yours from a previous chapter or a real analysis. Compute the condition number of \(X\) and of \(X^T X\). Note the ratio. Compute the OLS coefficients via the explicit-inverse formula and via
qr.coef. Compare the two answers in their last few digits.
16.14 Further reading
- (Goldberg, 1991), ‘What every computer scientist should know about floating-point arithmetic’, the canonical introduction. It is freely available at
dl.acm.org. - (Higham, 2002), Accuracy and Stability of Numerical Algorithms, 2nd ed., the standard reference. It is dense.
- (Trefethen & Bau III, 1997), Numerical Linear Algebra. The treatment of conditioning and stability in chapters 12 to 15 is the clearest available.
- The R documentation at
?.Machineand thematrixStatspackage vignettes for stable implementations of common reductions.