15 / 16 · Numerical Computation
Conditioning and numerical stability
What changes when a computer does the arithmetic: how sensitive a problem is, whether an algorithm adds error of its own, why the normal equations lose digits, and stable ways to compute softmax and variance.
The singular value decomposition · Matrices and linear systems
On this page 9
Solve
The solution is . Change the second entry of the right-hand side by , to , and the solution becomes . A relative change of the data of produced a relative change of the answer of , a factor of .
NumPy computes both solutions correctly to about 12 digits, so nothing went wrong in the arithmetic. The two equations describe two nearly parallel lines, and nearly parallel lines meet at a point that moves far when one of them shifts slightly. If the right-hand side came from a measurement with four significant digits, no algorithm could recover even the first digit of .
A small change in the data, a large change in the solution
Every number in the course so far was computed in floating point and treated as exact. How many digits of an answer do the data support, and how many does the algorithm lose on top of that? Two separate quantities answer this. The condition number belongs to the problem and measures how much it amplifies changes in its data. Backward stability belongs to the algorithm and says whether it adds more error than the data already carry.
Floating point in one paragraph#
A double-precision number has 53 significant bits, about 16 decimal digits, and an exponent that reaches about . Every input is rounded to the nearest such number, and every arithmetic operation is correctly rounded: the computed result equals with , for any of . Here is the unit roundoff, in double precision. Results above about overflow to infinity, and tiny results underflow to zero. The floating point note of the computer architecture course derives the bound and the formats. What matters here is the consequence: a datum carries a relative error of up to before any computation starts, and every operation may add another.
Lower precisions shrink the budget. Single precision has and overflows above . In bfloat16, with 8 significant bits, , so a problem that amplifies errors a hundredfold already loses most of its digits: , a relative error of 39%. This is why mixed-precision training keeps accumulations and some reductions in single precision.
The condition number of a problem#
A problem maps data to an answer . Its relative condition number is the largest amplification of a small relative change in the data:
where norms are Euclidean. For a function of one variable, the derivative gives the change to first order, and comparing relative changes leaves a ratio that depends only on and :
The square root has everywhere, so it halves relative errors. The exponential has , so is accurate only to about . The function has , which is huge near .
Take , where . The stored is off by at most relative, so may be off by up to relative. In double precision evaluates to , a relative error of , although the subtraction itself was exact (the section on cancellation below shows why). The error came from rounding the input, amplified by the problem.
The condition number of a matrix#
Consider the problem “solve for ”, with square and invertible, and change by . For the spectral norm , the largest stretch of the SVD note, the relative error is bounded by
Two inequalities, each from the definition of the matrix norm, multiply to give it:
The first holds because subtracting from leaves . Dividing the first inequality by and using from the second gives the bound.
The spectral norm is (SVD note), and is an SVD with largest singular value , so ; this gives the ratio of singular values. The bound is attained. Take , the left singular vector of , and , along that of . Then and , so the ratio of relative changes is .
Perturbations of itself obey the same law to first order. Subtract from and drop the second-order term :
The last line multiplies and divides by (Trefethen and Bau, 1997, Lecture 12).
Always , since ; for orthogonal matrices, whose singular values are all 1, and for singular ones, where . For the opening matrix the singular values are and , so , and the observed amplification of stays below it. The figure above shows the same effect with a milder matrix, .
The bound is normwise. An error of relative size in the norm may sit entirely in a component of much smaller than , which then has no correct digits; componentwise condition numbers exist for that case (Higham, 2002). Computing exactly also costs more than the solve: numpy.linalg.cond computes all singular values, an SVD, while LAPACK solvers estimate cheaply from the factorization they already have.
The Hilbert matrix#
The Hilbert matrix is the Gram matrix of the monomials on :
It is what the normal equations of polynomial least squares become with many evenly spread points in : the entry of is a Riemann sum of the integral above. In the computed values its condition number grows by a factor of about 30 per row, from at to at and at , beyond .
Solve by Gaussian elimination with partial pivoting, with computed in floating point, so that the exact solution of the intended problem is the vector of ones:
| relative error of | relative residual | |||
|---|---|---|---|---|
| 3 | ||||
| 5 | ||||
| 8 | ||||
| 10 | ||||
| 12 | ||||
| 13 |
The error of a solve grows with the condition number
The error grows with and stays below in every row: at about four of the sixteen digits survive, at none. The bound says how bad the error can get; in most rows it is several times smaller. The last column tells a different story, the subject of the next section.
Backward stability#
The relative residual , computed exactly from the stored numbers, stays below in every row, even where is entirely wrong. A small residual means that is the exact solution of a slightly different system. With , the matrix
satisfies , because . A rank-one matrix has spectral norm , its only nonzero singular value, so , and is exactly that relative residual (Rigal and Gaches, 1967). Elimination did its job perfectly, up to rounding; the answer is wrong because the problem is ill-conditioned.
This is the general pattern. An algorithm for is backward stable if its computed answer is the exact answer for slightly perturbed data: with . Such an algorithm makes an error no larger than an error in the data would cause, and the condition number converts the one into the other:
The second line is the definition of applied to the small perturbation .
Gaussian elimination with partial pivoting is backward stable in practice. Its backward error is a modest multiple of times the growth factor, the largest entry produced during elimination relative to the largest entry of (Trefethen and Bau, 1997, Lecture 22). The linear systems note derives why pivoting bounds the growth by : multipliers at most 1 at most double the entries per step. Contrived matrices reach that bound. On the matrices met in practice the growth stays small; this is an observation, not a theorem (Trefethen and Bau, Lecture 22).
Cholesky factorization of a positive definite matrix needs no pivoting at all, because its entries cannot grow. The diagonal entry of in row is
so every . This is why Gaussian processes use it.
A stable algorithm cannot rescue an ill-conditioned problem; it can only avoid making things worse. The cure lies in the problem: rescale features, drop near-duplicate ones, or regularize. Adding to a positive semidefinite matrix with eigenvalues shifts every eigenvalue by , so its condition number becomes . That is one reason why ridge regression and the jitter added to kernel matrices help numerically as well as statistically.
Least squares: why the normal equations square κ#
Least squares, , can be solved through the normal equations of the least squares note, or through a factorization of itself. Forming squares every singular value, and therefore their ratio. With the thin SVD , where :
A backward stable solver applied to the normal equations therefore loses about digits. The QR factorization of the orthogonality note avoids the squaring. has orthonormal columns, so for every and , and the solution comes from the triangular system .
Householder QR and the SVD are backward stable for least squares (Trefethen and Bau, 1997, Lecture 19), so their error is the condition number of the least-squares problem times about . That condition number, for perturbations of , is at most , where is the angle between and the column space of (Trefethen and Bau, Lecture 18; Bindel, 2025).
Derivation: where κ² tan θ comes from
Perturb to in the normal equations . With the residual , keeping first-order terms,
with . The second term is bounded by , giving . In the first, , and , so
The term belongs to the problem when the residual is large, but it vanishes when the fit is exact (), while the normal equations pay always.
Take a matrix with singular values spaced evenly on a log scale from 1 to , and the true weights . The relative errors of the three solvers:
| residual | normal equations | QR | SVD (lstsq) | |
|---|---|---|---|---|
| 0 | ||||
| 0 | ||||
At the normal equations keep five digits; QR and the SVD keep eleven with an exact fit and seven with a residual. The least squares note shows the same gap on polynomial features. The formula is for derivations; numerical code factorizes .
Log-sum-exp and the stable softmax#
The softmax, the cross-entropy loss and every mixture model need
Computed as written it overflows as soon as one exceeds about 709 in double precision or 88.7 in single precision, and the probabilities become . The remedy is to factor out the largest exponential before summing. With ,
Every shifted exponent is at most 0, so the sum cannot overflow, and the term with equals 1, so it cannot be zero. The softmax is unchanged by the shift because the factor cancels between numerator and denominator. The sum lies between 1 and , which also bounds the result:
For the naive formulas give and the probabilities . The shifted ones give and , the softmax of . The bounds make lse a smooth maximum; it is convex, as shown in the convexity note, and its gradient is the softmax: by the chain rule, . The deep learning course works through the same shift in single precision for the cross-entropy loss, including the underflow of very small probabilities (why log-softmax is numerically stable).
The two-class case is the softplus , the logistic loss of a margin. The same factoring, for , gives
and the last logarithm should be computed by log1p, which is accurate for tiny arguments where would round to 1. At the naive formula gives and the stable one . At the naive formula gives , because rounds to 1, and the stable one gives .
Catastrophic cancellation#
Subtraction of two nearly equal numbers is the most common source of lost digits. The absolute errors of the operands survive the subtraction, but the result is small, so the relative error is large. If and with , then , and the triangle inequality gives
The factor is the condition number of subtraction when both operands carry errors. In the example above it is , twice the found there, where only was perturbed.
The subtraction itself is exact when , for positive doubles and . Let . Doubles in that range are spaced apart, and doubles above it are spaced by multiples of that, so both and are integer multiples of . Then with , so : the difference fits in 53 bits and is itself a double, which correct rounding returns unchanged. The damage comes from errors made earlier.
Take . Its limit at 0 is , and the problem is well conditioned there. The Taylor series gives
The formula as written is not:
| correct digits | ||
|---|---|---|
| 8 | ||
| 4 | ||
| 0 |
At , rounds to exactly 1. The algorithm is unstable for a well-conditioned problem: the rounding error of , at most , meets the condition number of the subtraction. The identity removes the subtraction, and is correct to full precision at all three points: , and , matching . Finite-difference derivatives suffer from the same cancellation, which is why their error grows again for very small steps (finite differences).
The one-pass formula for the variance, , subtracts two large, nearly equal numbers. For the data the squares are about , where neighbouring doubles are 2 apart, and the formula returns instead of . The two-pass formula, which subtracts the mean first and then averages the squared deviations, returns . For streaming data, Welford’s update (Welford, 1962) keeps a running mean and a running sum of squared deviations, so it never forms the large squares (Higham, 2002, §1.9).
The same care applies to the batch statistics of the normalization layers of deep learning, where activations with a large mean and a small spread are common and the arithmetic is often single or half precision.
What you should remember#
- Every input and operation carries a relative error up to : in double, in single, in bfloat16.
- for one variable; for .
- Error backward error; a stable algorithm loses about digits.
- A small residual means a small backward error, not an accurate solution.
- : solve least squares with QR or the SVD.
- Shift log-sum-exp by the maximum; rewrite formulas that subtract nearly equal numbers.
Code#
The opening system, the subtraction near 1, the Hilbert matrices with Gaussian elimination written out, least squares three ways, cancellation, and the stable log-sum-exp and softplus. The elimination, the power iteration and the sums use plain loops so that the figure, which repeats them, gets the same digits. Exact digits of the least-squares experiment can differ slightly across platforms and library versions.
import numpy as np
from math import comb
from fractions import Fraction
u = 2.0 ** -53 # unit roundoff of double precision
# a nearly singular 2 x 2 system: a change of 1e-4 in b moves the solution from (1, 1) to (0, 2)
A = np.array([[1, 1], [1, 1.0001]])
print(np.linalg.solve(A, [2, 2.0001]), np.linalg.solve(A, [2, 2.0002]).round(10), round(np.linalg.cond(A)))
# [1. 1.] [0. 2.] 40002
# subtraction near 1 is ill conditioned: kappa = |x / (x - 1)| = 1e7 amplifies the representation error of x, at most u
x = 1.0000001
print(x - 1, abs((x - 1) - 1e-7) / 1e-7)
# 1.0000000005838672e-07 5.838672220806777e-10
# Gaussian elimination with partial pivoting, written out so that the figure can repeat it operation by operation;
# sums run left to right (Python's built-in sum() compensates rounding errors, which would change the digits)
def dot(p, q):
s = 0.0
for a, c in zip(p, q):
s += a * c
return s
def gepp(A, b):
n = len(A); A = [row[:] for row in A]; b = b[:]
for k in range(n):
p = max(range(k, n), key=lambda i: abs(A[i][k]))
A[k], A[p] = A[p], A[k]; b[k], b[p] = b[p], b[k]
for i in range(k + 1, n):
m = A[i][k] / A[k][k]
for j in range(k, n):
A[i][j] = A[i][j] - m * A[k][j]
b[i] = b[i] - m * b[k]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = b[i]
for j in range(i + 1, n):
s = s - A[i][j] * x[j]
x[i] = s / A[i][i]
return x
def power(M, it=2000): # the largest eigenvalue of a symmetric positive definite matrix
n = len(M); v = [1.0] * n; lam = 0.0
for _ in range(it):
w = [dot(M[i], v) for i in range(n)]
lam = dot(w, v) / dot(v, v)
s = max(abs(t) for t in w); v = [t / s for t in w]
return lam
def hilbert_inverse(n): # the exact inverse of the Hilbert matrix has integer entries
return [[(-1) ** (i + j) * (i + j - 1) * comb(n + i - 1, n - j) * comb(n + j - 1, n - i) * comb(i + j - 2, i - 1) ** 2
for j in range(1, n + 1)] for i in range(1, n + 1)]
# the Hilbert matrix H_ij = 1/(i + j - 1): solve H x = H 1 and compare the error with kappa * u
norm = lambda v: dot(v, v) ** 0.5
for n in range(3, 14):
H = [[1.0 / (i + j + 1) for j in range(n)] for i in range(n)]
kappa = power(H) * power([[float(t) for t in row] for row in hilbert_inverse(n)]) # lambda_max(H) / lambda_min(H)
b = [dot(H[i], [1.0] * n) for i in range(n)]
xh = gepp(H, b)
err = norm([t - 1 for t in xh]) / n ** 0.5
r = [float(Fraction(b[i]) - sum(Fraction(H[i][j]) * Fraction(xh[j]) for j in range(n))) for i in range(n)]
res = norm(r) / (power(H) * norm(xh)) # exact residual of the stored data, relative: a backward error
print(n, f'{kappa:.2e} {kappa * u:.1e} {err:.1e} {res:.1e}')
# n, kappa, kappa * u, relative error of x, relative residual
# 3 5.24e+02 5.8e-14 8.0e-15 7.8e-17
# 4 1.55e+04 1.7e-12 3.9e-13 6.9e-17
# 5 4.77e+05 5.3e-11 3.5e-13 4.9e-17
# 6 1.50e+07 1.7e-09 3.1e-10 2.0e-17
# 7 4.75e+08 5.3e-08 1.4e-08 4.9e-17
# 8 1.53e+10 1.7e-06 2.2e-07 2.4e-17
# 9 4.93e+11 5.5e-05 1.0e-05 9.6e-17
# 10 1.60e+13 1.8e-03 1.6e-04 2.7e-17
# 11 5.23e+14 5.8e-02 4.6e-03 4.7e-17
# 12 1.71e+16 1.9e+00 1.7e-01 5.6e-17
# 13 5.63e+17 6.2e+01 2.0e+00 3.3e-17
# least squares: normal equations against QR and the SVD, with a zero and with a nonzero residual
rng = np.random.default_rng(0)
m, d = 100, 6
U, _ = np.linalg.qr(rng.normal(size=(m, m))); V, _ = np.linalg.qr(rng.normal(size=(d, d)))
for kap in (1e3, 1e6):
X = U[:, :d] @ np.diag(np.logspace(0, -np.log10(kap), d)) @ V.T # singular values from 1 down to 1/kappa
w = np.ones(d)
for r in (np.zeros(m), 1e-2 * U[:, d]): # the residual is orthogonal to the columns of X
yv = X @ w + r
ne = np.linalg.solve(X.T @ X, X.T @ yv)
Q, R = np.linalg.qr(X); qr = np.linalg.solve(R, Q.T @ yv)
sv = np.linalg.lstsq(X, yv, rcond=None)[0]
e = lambda z: f'{np.linalg.norm(z - w) / np.linalg.norm(w):.0e}'
print(f'{np.linalg.cond(X):.0e} {np.linalg.cond(X.T @ X):.0e} |r|={np.linalg.norm(r):.0e}', e(ne), e(qr), e(sv), end=' | ')
print()
# 1e+03 1e+06 |r|=0e+00 3e-12 8e-15 7e-15 | 1e+03 1e+06 |r|=1e-02 2e-12 6e-14 5e-14 |
# 1e+06 1e+12 |r|=0e+00 7e-06 3e-12 2e-12 | 1e+06 1e+12 |r|=1e-02 6e-06 4e-08 4e-08 |
# catastrophic cancellation: (1 - cos x) / x^2 tends to 1/2, the rewrite 2 sin^2(x/2) / x^2 does not cancel
for t in (1e-4, 1e-6, 1e-8):
print(t, (1 - np.cos(t)) / t**2, 2 * np.sin(t / 2) ** 2 / t**2, end=' | ')
print()
# 0.0001 0.4999999969612645 0.4999999995833334 | 1e-06 0.5000444502911705 0.4999999999999583 | 1e-08 0.0 0.5
# the variance of 1e8 + (1, 2, 3): the one-pass formula E[x^2] - E[x]^2 cancels to 0, the two-pass formula does not
z = 1e8 + np.array([1., 2, 3])
print(np.mean(z**2) - np.mean(z) ** 2, np.mean((z - z.mean()) ** 2))
# 0.0 0.6666666666666666
# log-sum-exp and softmax: the naive formulas overflow, the shifted ones do not
s = np.array([1000., 999, 998])
with np.errstate(over='ignore', invalid='ignore'):
print(np.log(np.exp(s).sum()), np.exp(s) / np.exp(s).sum())
mx = s.max()
print(mx + np.log(np.exp(s - mx).sum()), (np.exp(s - mx) / np.exp(s - mx).sum()).round(4))
# inf [nan nan nan]
# 1000.4076059644444 [0.6652 0.2447 0.09 ]
# softplus log(1 + e^t): stable as max(t, 0) + log1p(e^-|t|)
with np.errstate(over='ignore'):
print(np.log(1 + np.exp(800.)), 800 + np.log1p(np.exp(-800.)), np.log(1 + np.exp(-40.)), np.log1p(np.exp(-40.)))
# inf 800.0 0.0 4.248354255291589e-18
Next#
Every method in this note factorizes the matrix: elimination, Cholesky, QR and the SVD cost on the order of operations and numbers of memory. For a million unknowns that is 8 TB of storage, while a sparse matrix of the same size with about five nonzeros per row fits in 64 MB and is multiplied by a vector in milliseconds. The next note computes with such products alone. The power method finds the largest eigenvalue, and conjugate gradient solves a positive definite system in a number of steps set by the square root of the condition number met here.
References#
- L. N. Trefethen, D. Bau III. Numerical Linear Algebra. SIAM, 1997. Lecture 12 (conditioning and condition numbers), Lecture 13 (floating point arithmetic), Lectures 14–15 (stability, backward stability), Lectures 18–19 (conditioning and stability of least squares), Lecture 22 (stability of Gaussian elimination).
- N. J. Higham. Accuracy and Stability of Numerical Algorithms, 2nd ed. SIAM, 2002. Chapter 1 (§1.7 cancellation, §1.9 computing the sample variance); also perturbation theory for linear systems, including componentwise condition numbers, and LU factorization with the growth factor.
- D. Bindel. Sensitivity analysis and ill-posedness. Lecture notes, CS 6210 Matrix Computations, Cornell University, 1 October 2025. The sensitivity of least squares to perturbations of the matrix and of the right-hand side.
- J. L. Rigal, J. Gaches. On the compatibility of a given solution with the data of a linear system. Journal of the ACM, 14(3), 1967.
- B. P. Welford. Note on a method for calculating corrected sums of squares and products. Technometrics, 4(3), 1962.