Course contents 15 / 16

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.

On this page 9

Solve

(1111.0001)x=(22.0001).\begin{pmatrix} 1 & 1 \\ 1 & 1.0001 \end{pmatrix} x = \begin{pmatrix} 2 \\ 2.0001 \end{pmatrix} .

The solution is x=(1,1)x = (1, 1). Change the second entry of the right-hand side by 10−410^{-4}, to 2.00022.0002, and the solution becomes (0,2)(0, 2). A relative change of the data of 3.5⋅10−53.5 \cdot 10^{-5} produced a relative change of the answer of 11, a factor of 28,00028{,}000.

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 xx.

Figure

A small change in the data, a large change in the solution

Intersecting lines for a well and a badly conditioned systemTwo panels. Left, two perpendicular lines; the shifted dashed line crosses the first one almost at the same point. Right, two nearly parallel lines; the shifted dashed line crosses the first one far from the original point, and an arrow shows the large move of the solution.κ = 1: perpendicular lines(1, 1)the solution moves by 0.035κ = 42: nearly parallel lines(1, 1)the solution moves by 0.707Intersecting lines for a well and a badly conditioned systemTwo panels. Left, two perpendicular lines; the shifted dashed line crosses the first one almost at the same point. Right, two nearly parallel lines; the shifted dashed line crosses the first one far from the original point, and an arrow shows the large move of the solution.κ = 1: perpendicular lines(1, 1)the solution moves by 0.035κ = 42: nearly parallel lines(1, 1)the solution moves by 0.707
Two 2 × 2 systems with solution (1, 1), drawn as two lines; the dashed line has its right-hand side raised by 0.05. Left, perpendicular lines (κ = 1): the intersection moves by 0.035. Right, x₁ + x₂ = 2 and x₁ + 1.1x₂ = 2.1 (κ = 42.1): it moves to (0.5, 1.5), a relative change 29 times larger.

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 10±30810^{\pm 308}. Every input is rounded to the nearest such number, and every arithmetic operation is correctly rounded: the computed result fl(a∘b)\mathrm{fl}(a \circ b) equals (a∘b)(1+δ)(a \circ b)(1 + \delta) with ∣δ∣≤u\lvert\delta\rvert \le u, for ∘\circ any of +,−,×,/+, -, \times, /. Here uu is the unit roundoff, u=2−53≈1.1⋅10−16u = 2^{-53} \approx 1.1 \cdot 10^{-16} in double precision. Results above about 1.8⋅103081.8 \cdot 10^{308} 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 uu before any computation starts, and every operation may add another.

Lower precisions shrink the budget. Single precision has u=2−24≈6.0⋅10−8u = 2^{-24} \approx 6.0 \cdot 10^{-8} and overflows above 3.4⋅10383.4 \cdot 10^{38}. In bfloat16, with 8 significant bits, u=2−8≈3.9⋅10−3u = 2^{-8} \approx 3.9 \cdot 10^{-3}, so a problem that amplifies errors a hundredfold already loses most of its digits: 100u≈0.39100u \approx 0.39, 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 xx to an answer f(x)f(x). Its relative condition number is the largest amplification of a small relative change in the data:

κf(x)=lim⁡ε→0 sup⁡∥δx∥≤ε∥x∥∥δf∥/∥f(x)∥∥δx∥/∥x∥,δf=f(x+δx)−f(x),\begin{aligned} \kappa_f(x) &= \lim_{\varepsilon \to 0}\ \sup_{\lVert\delta x\rVert \le \varepsilon\lVert x\rVert} \frac{\lVert\delta f\rVert / \lVert f(x)\rVert}{\lVert\delta x\rVert / \lVert x\rVert} , \\ \delta f &= f(x + \delta x) - f(x) , \end{aligned}

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 ff and xx:

f(x+δx)−f(x)=f′(x) δx+o(δx)f(x+δx)−f(x)f(x)=xf′(x)f(x)⋅δxx+o(δxx)κf(x)=∣x f′(x)f(x)∣.\begin{aligned} f(x + \delta x) - f(x) &= f'(x)\,\delta x + o(\delta x) \\ \frac{f(x + \delta x) - f(x)}{f(x)} &= \frac{x f'(x)}{f(x)} \cdot \frac{\delta x}{x} + o\Big(\frac{\delta x}{x}\Big) \\ \kappa_f(x) &= \left\lvert \frac{x\, f'(x)}{f(x)} \right\rvert . \end{aligned}

The square root has κ=∣x⋅12x/x∣=12\kappa = \lvert x \cdot \frac{1}{2\sqrt x} / \sqrt x\rvert = \frac12 everywhere, so it halves relative errors. The exponential has κ=∣xex/ex∣=∣x∣\kappa = \lvert x e^x / e^x\rvert = \lvert x\rvert, so e100e^{100} is accurate only to about 100u100u. The function f(x)=x−1f(x) = x - 1 has κ=∣x/(x−1)∣\kappa = \lvert x/(x - 1)\rvert, which is huge near x=1x = 1.

Take x=1.0000001x = 1.0000001, where κ=107\kappa = 10^7. The stored xx is off by at most uu relative, so x−1x - 1 may be off by up to 107u=1.1⋅10−910^7 u = 1.1 \cdot 10^{-9} relative. In double precision x−1x - 1 evaluates to 1.0000000005838672⋅10−71.0000000005838672 \cdot 10^{-7}, a relative error of 5.8⋅10−105.8 \cdot 10^{-10}, 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 Ax=bAx = b for xx”, with AA square and invertible, and change bb by δb\delta b. For the spectral norm ∥A∥\lVert A\rVert, the largest stretch σmax⁡\sigma_{\max} of the SVD note, the relative error is bounded by

∥δx∥∥x∥≤κ(A) ∥δb∥∥b∥,κ(A)=∥A∥ ∥A−1∥=σmax⁡(A)σmin⁡(A).\begin{aligned} \frac{\lVert\delta x\rVert}{\lVert x\rVert} &\le \kappa(A)\,\frac{\lVert\delta b\rVert}{\lVert b\rVert} , \\ \kappa(A) &= \lVert A\rVert\,\lVert A^{-1}\rVert = \frac{\sigma_{\max}(A)}{\sigma_{\min}(A)} . \end{aligned}

Two inequalities, each from the definition of the matrix norm, multiply to give it:

∥δx∥=∥A−1δb∥≤∥A−1∥ ∥δb∥,∥b∥=∥Ax∥≤∥A∥ ∥x∥.\begin{aligned} \lVert\delta x\rVert &= \lVert A^{-1}\delta b\rVert \le \lVert A^{-1}\rVert\,\lVert\delta b\rVert , \\ \lVert b\rVert &= \lVert Ax\rVert \le \lVert A\rVert\,\lVert x\rVert . \end{aligned}

The first holds because subtracting Ax=bAx = b from A(x+δx)=b+δbA(x + \delta x) = b + \delta b leaves A δx=δbA\,\delta x = \delta b. Dividing the first inequality by ∥x∥\lVert x\rVert and using 1/∥x∥≤∥A∥/∥b∥1/\lVert x\rVert \le \lVert A\rVert/\lVert b\rVert from the second gives the bound.

The spectral norm is ∥A∥=σmax⁡\lVert A\rVert = \sigma_{\max} (SVD note), and A−1=VΣ−1U⊤A^{-1} = V\Sigma^{-1}U^\top is an SVD with largest singular value 1/σmin⁡1/\sigma_{\min}, so ∥A−1∥=1/σmin⁡\lVert A^{-1}\rVert = 1/\sigma_{\min}; this gives the ratio of singular values. The bound is attained. Take b=u1b = u_1, the left singular vector of σmax⁡\sigma_{\max}, and δb=εun\delta b = \varepsilon u_n, along that of σmin⁡\sigma_{\min}. Then x=v1/σmax⁡x = v_1/\sigma_{\max} and δx=εvn/σmin⁡\delta x = \varepsilon v_n/\sigma_{\min}, so the ratio of relative changes is σmax⁡/σmin⁡\sigma_{\max}/\sigma_{\min}.

Perturbations of AA itself obey the same law to first order. Subtract Ax=bAx = b from (A+δA)(x+δx)=b(A + \delta A)(x + \delta x) = b and drop the second-order term δA δx\delta A\,\delta x:

A δx≈−δA x,∥δx∥≲∥A−1∥ ∥δA∥ ∥x∥,∥δx∥∥x∥≲κ(A) ∥δA∥∥A∥.\begin{aligned} A\,\delta x &\approx -\delta A\, x , \\ \lVert\delta x\rVert &\lesssim \lVert A^{-1}\rVert\,\lVert\delta A\rVert\,\lVert x\rVert , \\ \frac{\lVert\delta x\rVert}{\lVert x\rVert} &\lesssim \kappa(A)\,\frac{\lVert\delta A\rVert}{\lVert A\rVert} . \end{aligned}

The last line multiplies and divides by ∥A∥\lVert A\rVert (Trefethen and Bau, 1997, Lecture 12).

Always κ≥1\kappa \ge 1, since σmax⁡≥σmin⁡\sigma_{\max} \ge \sigma_{\min}; κ=1\kappa = 1 for orthogonal matrices, whose singular values are all 1, and κ=∞\kappa = \infty for singular ones, where σmin⁡=0\sigma_{\min} = 0. For the opening matrix the singular values are 2.000052.00005 and 0.000050.00005, so κ=4.0⋅104\kappa = 4.0 \cdot 10^4, and the observed amplification of 28,00028{,}000 stays below it. The figure above shows the same effect with a milder matrix, κ=42\kappa = 42.

The bound is normwise. An error of relative size ε\varepsilon in the norm may sit entirely in a component of xx much smaller than ε∥x∥\varepsilon\lVert x\rVert, which then has no correct digits; componentwise condition numbers exist for that case (Higham, 2002). Computing κ\kappa exactly also costs more than the solve: numpy.linalg.cond computes all singular values, an SVD, while LAPACK solvers estimate κ\kappa cheaply from the factorization they already have.

The Hilbert matrix#

The Hilbert matrix Hij=1/(i+j−1)H_{ij} = 1/(i + j - 1) is the Gram matrix of the monomials 1,t,…,tn−11, t, \dots, t^{n-1} on [0,1][0, 1]:

∫01ti−1tj−1 dt=1i+j−1.\int_0^1 t^{i-1}t^{j-1}\,dt = \frac{1}{i + j - 1} .

It is what the normal equations of polynomial least squares become with many evenly spread points t1,…,tNt_1, \dots, t_N in [0,1][0, 1]: the entry 1N∑ktki+j−2\frac1N\sum_k t_k^{i+j-2} of 1NX⊤X\frac1N X^\top X 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 524524 at n=3n = 3 to 1.6⋅10131.6 \cdot 10^{13} at n=10n = 10 and 5.6⋅10175.6 \cdot 10^{17} at n=13n = 13, beyond 1/u1/u.

Solve Hx=bHx = b by Gaussian elimination with partial pivoting, with b=H(1,…,1)⊤b = H(1, \dots, 1)^\top computed in floating point, so that the exact solution of the intended problem is the vector of ones:

nnκ(H)\kappa(H)κu\kappa urelative error of x^\hat xrelative residual
35.2⋅1025.2 \cdot 10^{2}5.8⋅10−145.8 \cdot 10^{-14}8.0⋅10−158.0 \cdot 10^{-15}7.8⋅10−177.8 \cdot 10^{-17}
54.8⋅1054.8 \cdot 10^{5}5.3⋅10−115.3 \cdot 10^{-11}3.5⋅10−133.5 \cdot 10^{-13}4.9⋅10−174.9 \cdot 10^{-17}
81.5⋅10101.5 \cdot 10^{10}1.7⋅10−61.7 \cdot 10^{-6}2.2⋅10−72.2 \cdot 10^{-7}2.4⋅10−172.4 \cdot 10^{-17}
101.6⋅10131.6 \cdot 10^{13}1.8⋅10−31.8 \cdot 10^{-3}1.6⋅10−41.6 \cdot 10^{-4}2.7⋅10−172.7 \cdot 10^{-17}
121.7⋅10161.7 \cdot 10^{16}1.91.90.170.175.6⋅10−175.6 \cdot 10^{-17}
135.6⋅10175.6 \cdot 10^{17}62622.02.03.3⋅10−173.3 \cdot 10^{-17}
Figure

The error of a solve grows with the condition number

Relative error against the condition numberA log–log plot: eleven points rise from left to right almost along the slanted dashed line κu, staying below it; the last point reaches the level of 100% error.110⁴10⁸10¹²10¹⁶110⁻⁴10⁻⁸10⁻¹²10⁻¹⁶condition number κ100%: no correct digitsn = 3n = 6n = 9n = 11n = 13κuu = 1.1 · 10⁻¹⁶relative errorHilbert matrices, n = 3…13κuRelative error against the condition numberA log–log plot: eleven points rise from left to right almost along the slanted dashed line κu, staying below it; the last point reaches the level of 100% error.110⁴10⁸10¹²10¹⁶110⁻⁴10⁻⁸10⁻¹²10⁻¹⁶condition number κ100%: no correct digitsn = 3n = 6n = 9n = 11n = 13κuu = 1.1 · 10⁻¹⁶relative errorHilbert matrices, n = 3…13κu
Relative error ‖x̂ − 1‖/‖1‖ against κ(H) for Hilbert systems Hx = H·1 of orders 3 to 13, solved by elimination with partial pivoting in double precision; both axes logarithmic. Every point lies below the dashed line κu. At n = 10 four digits remain; at n = 13, with κ beyond 1/u, none.

The error grows with κ\kappa and stays below κu\kappa u in every row: at n=10n = 10 about four of the sixteen digits survive, at n=13n = 13 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 ∥b−Hx^∥/(∥H∥ ∥x^∥)\lVert b - H\hat x\rVert/(\lVert H\rVert\,\lVert\hat x\rVert), computed exactly from the stored numbers, stays below 10−1610^{-16} in every row, even where x^\hat x is entirely wrong. A small residual means that x^\hat x is the exact solution of a slightly different system. With r=b−Hx^r = b - H\hat x, the matrix

ΔH=r x^⊤∥x^∥2\Delta H = \frac{r\,\hat x^\top}{\lVert\hat x\rVert^2}

satisfies (H+ΔH)x^=b(H + \Delta H)\hat x = b, because ΔH x^=r\Delta H\,\hat x = r. A rank-one matrix rx^⊤r\hat x^\top has spectral norm ∥r∥ ∥x^∥\lVert r\rVert\,\lVert\hat x\rVert, its only nonzero singular value, so ∥ΔH∥=∥r∥/∥x^∥\lVert\Delta H\rVert = \lVert r\rVert/\lVert\hat x\rVert, and ∥ΔH∥/∥H∥\lVert\Delta H\rVert/\lVert H\rVert 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 ff is backward stable if its computed answer is the exact answer for slightly perturbed data: y^=f(x+Δx)\hat y = f(x + \Delta x) with ∥Δx∥/∥x∥=O(u)\lVert\Delta x\rVert/\lVert x\rVert = O(u). 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:

y^−f(x)=f(x+Δx)−f(x),∥y^−f(x)∥∥f(x)∥≲κf(x) ∥Δx∥∥x∥=κf(x)⋅O(u).\begin{aligned} \hat y - f(x) &= f(x + \Delta x) - f(x) , \\ \frac{\lVert\hat y - f(x)\rVert}{\lVert f(x)\rVert} &\lesssim \kappa_f(x)\,\frac{\lVert\Delta x\rVert}{\lVert x\rVert} = \kappa_f(x) \cdot O(u) . \end{aligned}

The second line is the definition of κf\kappa_f applied to the small perturbation Δx\Delta x.

Gaussian elimination with partial pivoting is backward stable in practice. Its backward error is a modest multiple of uu times the growth factor, the largest entry produced during elimination relative to the largest entry of AA (Trefethen and Bau, 1997, Lecture 22). The linear systems note derives why pivoting bounds the growth by 2n−12^{n-1}: 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 A=LL⊤A = LL^\top of a positive definite matrix needs no pivoting at all, because its entries cannot grow. The diagonal entry of A=LL⊤A = LL^\top in row ii is

aii=∑k≤ilik2,a_{ii} = \textstyle\sum_{k \le i} l_{ik}^2 ,

so every ∣lik∣≤aii\lvert l_{ik}\rvert \le \sqrt{a_{ii}}. 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 λI\lambda I to a positive semidefinite matrix with eigenvalues λmax⁡≥⋯≥λmin⁡≥0\lambda_{\max} \ge \dots \ge \lambda_{\min} \ge 0 shifts every eigenvalue by λ\lambda, so its condition number becomes (λmax⁡+λ)/(λmin⁡+λ)≤(λmax⁡+λ)/λ(\lambda_{\max} + \lambda)/(\lambda_{\min} + \lambda) \le (\lambda_{\max} + \lambda)/\lambda. 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, min⁡w∥Xw−y∥2\min_w\lVert Xw - y\rVert^2, can be solved through the normal equations X⊤Xw=X⊤yX^\top X w = X^\top y of the least squares note, or through a factorization of XX itself. Forming X⊤XX^\top X squares every singular value, and therefore their ratio. With the thin SVD X=UΣV⊤X = U\Sigma V^\top, where U⊤U=IU^\top U = I:

X⊤X=VΣU⊤UΣV⊤=VΣ2V⊤,κ(X⊤X)=σmax⁡2σmin⁡2=κ(X)2.\begin{aligned} X^\top X &= V\Sigma U^\top U\Sigma V^\top = V\Sigma^2 V^\top , \\ \kappa(X^\top X) &= \frac{\sigma_{\max}^2}{\sigma_{\min}^2} = \kappa(X)^2 . \end{aligned}

A backward stable solver applied to the normal equations therefore loses about 2log⁡10κ(X)2\log_{10}\kappa(X) digits. The QR factorization X=QRX = QR of the orthogonality note avoids the squaring. QQ has orthonormal columns, so ∥Xv∥=∥Rv∥\lVert Xv\rVert = \lVert Rv\rVert for every vv and κ(R)=κ(X)\kappa(R) = \kappa(X), and the solution comes from the triangular system Rw=Q⊤yRw = Q^\top y.

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 uu. That condition number, for perturbations of XX, is at most κ+κ2tan⁡θ\kappa + \kappa^2\tan\theta, where θ\theta is the angle between yy and the column space of XX (Trefethen and Bau, Lecture 18; Bindel, 2025).

Derivation: where κ² tan θ comes from

Perturb XX to X+δXX + \delta X in the normal equations X⊤(y−Xw)=0X^\top(y - Xw) = 0. With the residual r=y−Xwr = y - Xw, keeping first-order terms,

δX⊤r−X⊤(δX w+X δw)=0,δw=(X⊤X)−1δX⊤r−X+δX w,\begin{aligned} \delta X^\top r - X^\top(\delta X\, w + X\,\delta w) &= 0 , \\ \delta w &= (X^\top X)^{-1}\delta X^\top r - X^{+}\delta X\, w , \end{aligned}

with X+=(X⊤X)−1X⊤X^{+} = (X^\top X)^{-1}X^\top. The second term is bounded by ∥δX∥∥w∥/σmin⁡\lVert\delta X\rVert\lVert w\rVert/\sigma_{\min}, giving κ\kappa. In the first, ∥(X⊤X)−1∥=1/σmin⁡2\lVert(X^\top X)^{-1}\rVert = 1/\sigma_{\min}^2, ∥r∥=∥y∥sin⁡θ\lVert r\rVert = \lVert y\rVert\sin\theta and ∥w∥≥∥Xw∥/σmax⁡=∥y∥cos⁡θ/σmax⁡\lVert w\rVert \ge \lVert Xw\rVert/\sigma_{\max} = \lVert y\rVert\cos\theta/\sigma_{\max}, so

∥(X⊤X)−1δX⊤r∥∥w∥≤κ2tan⁡θ ∥δX∥∥X∥.\frac{\lVert(X^\top X)^{-1}\delta X^\top r\rVert}{\lVert w\rVert} \le \kappa^2\tan\theta\,\frac{\lVert\delta X\rVert}{\lVert X\rVert} .

The κ2\kappa^2 term belongs to the problem when the residual is large, but it vanishes when the fit is exact (θ=0\theta = 0), while the normal equations pay κ(X⊤X) u=κ2u\kappa(X^\top X)\,u = \kappa^2 u always.

Take a 100×6100 \times 6 matrix XX with singular values spaced evenly on a log scale from 1 to 1/κ(X)1/\kappa(X), and the true weights w=(1,…,1)w = (1, \dots, 1). The relative errors of the three solvers:

κ(X)\kappa(X)residual ∥y−Xw∥\lVert y - Xw\rVertnormal equationsQRSVD (lstsq)
10310^303⋅10−123 \cdot 10^{-12}8⋅10−158 \cdot 10^{-15}7⋅10−157 \cdot 10^{-15}
10310^310−210^{-2}2⋅10−122 \cdot 10^{-12}6⋅10−146 \cdot 10^{-14}5⋅10−145 \cdot 10^{-14}
10610^607⋅10−67 \cdot 10^{-6}3⋅10−123 \cdot 10^{-12}2⋅10−122 \cdot 10^{-12}
10610^610−210^{-2}6⋅10−66 \cdot 10^{-6}4⋅10−84 \cdot 10^{-8}4⋅10−84 \cdot 10^{-8}

At κ(X)=106\kappa(X) = 10^6 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 (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top y is for derivations; numerical code factorizes XX.

Log-sum-exp and the stable softmax#

The softmax, the cross-entropy loss and every mixture model need

lse⁡(z)=log⁡∑i=1Kezi.\operatorname{lse}(z) = \log\sum_{i=1}^K e^{z_i} .

Computed as written it overflows as soon as one ziz_i exceeds about 709 in double precision or 88.7 in single precision, and the probabilities ezi/∑jezje^{z_i}/\sum_j e^{z_j} become ∞/∞\infty/\infty. The remedy is to factor out the largest exponential before summing. With m=max⁡izim = \max_i z_i,

log⁡∑iezi=log⁡(em∑iezi−m)=m+log⁡∑iezi−m,softmax⁡(z)i=ezi−m∑jezj−m.\begin{aligned} \log\sum_i e^{z_i} &= \log\Big(e^{m}\sum_i e^{z_i - m}\Big) \\ &= m + \log\sum_i e^{z_i - m} , \\ \operatorname{softmax}(z)_i &= \frac{e^{z_i - m}}{\sum_j e^{z_j - m}} . \end{aligned}

Every shifted exponent is at most 0, so the sum cannot overflow, and the term with zi=mz_i = m equals 1, so it cannot be zero. The softmax is unchanged by the shift because the factor e−me^{-m} cancels between numerator and denominator. The sum lies between 1 and KK, which also bounds the result:

m≤lse⁡(z)≤m+log⁡K.m \le \operatorname{lse}(z) \le m + \log K .

For z=(1000,999,998)z = (1000, 999, 998) the naive formulas give lse⁡=∞\operatorname{lse} = \infty and the probabilities (nan,nan,nan)(\text{nan}, \text{nan}, \text{nan}). The shifted ones give 1000+log⁡(1+e−1+e−2)=1000.40761000 + \log(1 + e^{-1} + e^{-2}) = 1000.4076 and (0.665,0.245,0.090)(0.665, 0.245, 0.090), the softmax of (0,−1,−2)(0, -1, -2). 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, ∂lse⁡/∂zi=ezi/∑jezj\partial\operatorname{lse}/\partial z_i = e^{z_i}/\sum_j e^{z_j}. 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 log⁡(1+et)\log(1 + e^t), the logistic loss of a margin. The same factoring, log⁡(1+et)=t+log⁡(1+e−t)\log(1 + e^t) = t + \log(1 + e^{-t}) for t≥0t \ge 0, gives

log⁡(1+et)=max⁡(t,0)+log⁡(1+e−∣t∣),\log(1 + e^t) = \max(t, 0) + \log\big(1 + e^{-\lvert t\rvert}\big) ,

and the last logarithm should be computed by log1p, which is accurate for tiny arguments where 1+e−∣t∣1 + e^{-\lvert t\rvert} would round to 1. At t=800t = 800 the naive formula gives ∞\infty and the stable one 800800. At t=−40t = -40 the naive formula gives 00, because 1+4.2⋅10−181 + 4.2 \cdot 10^{-18} rounds to 1, and the stable one gives 4.25⋅10−184.25 \cdot 10^{-18}.

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 a^=a(1+ε1)\hat a = a(1 + \varepsilon_1) and b^=b(1+ε2)\hat b = b(1 + \varepsilon_2) with ∣εi∣≤ε\lvert\varepsilon_i\rvert \le \varepsilon, then (a^−b^)−(a−b)=aε1−bε2(\hat a - \hat b) - (a - b) = a\varepsilon_1 - b\varepsilon_2, and the triangle inequality gives

∣(a^−b^)−(a−b)∣∣a−b∣≤ε ∣a∣+∣b∣∣a−b∣.\frac{\lvert(\hat a - \hat b) - (a - b)\rvert}{\lvert a - b\rvert} \le \varepsilon\,\frac{\lvert a\rvert + \lvert b\rvert}{\lvert a - b\rvert} .

The factor (∣a∣+∣b∣)/∣a−b∣(\lvert a\rvert + \lvert b\rvert)/\lvert a - b\rvert is the condition number of subtraction when both operands carry errors. In the example x−1x - 1 above it is 2⋅1072 \cdot 10^7, twice the κ=107\kappa = 10^7 found there, where only xx was perturbed.

The subtraction itself is exact when b≤a≤2bb \le a \le 2b, for positive doubles aa and bb. Let 2e≤b<2e+12^e \le b \lt 2^{e+1}. Doubles in that range are spaced 2e−522^{e-52} apart, and doubles above it are spaced by multiples of that, so both aa and bb are integer multiples of 2e−522^{e-52}. Then a−b=k⋅2e−52a - b = k \cdot 2^{e-52} with 0≤a−b≤b<2e+10 \le a - b \le b \lt 2^{e+1}, so k<253k \lt 2^{53}: the difference fits in 53 bits and is itself a double, which correct rounding returns unchanged. The damage comes from errors made earlier.

Take (1−cos⁡x)/x2(1 - \cos x)/x^2. Its limit at 0 is 12\frac12, and the problem is well conditioned there. The Taylor series cos⁡x=1−x2/2+x4/24−…\cos x = 1 - x^2/2 + x^4/24 - \dots gives

f(x)=12−x224+O(x4),κf(x)=∣xf′(x)f(x)∣≈x2/121/2=x26.\begin{aligned} f(x) &= \tfrac12 - \tfrac{x^2}{24} + O(x^4) , \\ \kappa_f(x) &= \left\lvert\frac{x f'(x)}{f(x)}\right\rvert \approx \frac{x^2/12}{1/2} = \frac{x^2}{6} . \end{aligned}

The formula as written is not:

xx(1−cos⁡x)/x2(1 - \cos x)/x^2correct digits
10−410^{-4}0.499999996960.499999996968
10−610^{-6}0.500040.500044
10−810^{-8}000

At x=10−8x = 10^{-8}, cos⁡x=1−5⋅10−17\cos x = 1 - 5 \cdot 10^{-17} rounds to exactly 1. The algorithm is unstable for a well-conditioned problem: the rounding error of cos⁡x\cos x, at most uu, meets the condition number (1+cos⁡x)/(1−cos⁡x)≈4/x2(1 + \cos x)/(1 - \cos x) \approx 4/x^2 of the subtraction. The identity 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2) removes the subtraction, and 2sin⁡2(x/2)/x22\sin^2(x/2)/x^2 is correct to full precision at all three points: 0.499999999583330.49999999958333, 0.499999999999960.49999999999996 and 0.50.5, matching 12−x2/24\frac12 - x^2/24. 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, Var⁡=E[x2]−(E[x])2\operatorname{Var} = E[x^2] - (E[x])^2, subtracts two large, nearly equal numbers. For the data 108+(1,2,3)10^8 + (1, 2, 3) the squares are about 101610^{16}, where neighbouring doubles are 2 apart, and the formula returns 00 instead of 23\frac23. The two-pass formula, which subtracts the mean first and then averages the squared deviations, returns 0.66670.6667. 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 uu: 1.1⋅10−161.1 \cdot 10^{-16} in double, 6⋅10−86 \cdot 10^{-8} in single, 3.9⋅10−33.9 \cdot 10^{-3} in bfloat16.
  • κf=∣xf′(x)/f(x)∣\kappa_f = \lvert xf'(x)/f(x)\rvert for one variable; κ(A)=σmax⁡/σmin⁡\kappa(A) = \sigma_{\max}/\sigma_{\min} for Ax=bAx = b.
  • Error ≈κ×\approx \kappa \times backward error; a stable algorithm loses about log⁡10κ\log_{10}\kappa digits.
  • A small residual means a small backward error, not an accurate solution.
  • κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2: 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 n3n^3 operations and n2n^2 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#