Skip to content
BIASED

Conditioning and numerical stability

How many digits of an answer survive floating point: machine epsilon, the condition number of a problem and of a matrix, QR instead of the normal equations, log-sum-exp and a stable softmax, catastrophic cancellation, ill-conditioned optimization.

Floating-point numbers

The topic Duality ended with certificates: a primal point, a dual point and a gap that bounds how far both are from the optimum. Every number in such a certificate, like every gradient, solve and decomposition in this course, is computed in floating point. This topic asks how many digits of an answer survive.

A floating-point number stores a fixed number of significant bits and an exponent, like scientific notation in base 2. The gap between 11 and the next representable number is the machine epsilon εmach\varepsilon_{\text{mach}}. Each arithmetic operation returns the exact result rounded to the nearest representable number:

fl⁡(a∘b)=(a∘b)(1+δ),∣δ∣≤12 εmach,∘∈{+,−,×,/}.\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta), \qquad \lvert \delta \rvert \le \tfrac12\,\varepsilon_{\text{mach}}, \qquad \circ \in \{+, -, \times, /\}.

So a single operation is accurate to a relative error of about εmach\varepsilon_{\text{mach}}. The formats used in ML differ a lot:

Format Significant bits εmach\varepsilon_{\text{mach}} Largest number
float64 5353 2−52≈2.2⋅10−162^{-52} \approx 2.2 \cdot 10^{-16} 1.8⋅103081.8 \cdot 10^{308}
float32 2424 2−23≈1.2⋅10−72^{-23} \approx 1.2 \cdot 10^{-7} 3.4⋅10383.4 \cdot 10^{38}
bfloat16 88 2−7≈7.8⋅10−32^{-7} \approx 7.8 \cdot 10^{-3} 3.4⋅10383.4 \cdot 10^{38}
float16 1111 2−10≈9.8⋅10−42^{-10} \approx 9.8 \cdot 10^{-4} 6550465504

A relative error of 10−1610^{-16} leaves the first 1616 decimal digits intact, so float64 carries about 1616 significant digits.

Two consequences show up everywhere. First, adding to aa a positive number smaller than half the gap between aa and the next representable number changes nothing. Right after 11 that gap is εmach\varepsilon_{\text{mach}}, so in float64 1 + 1e-16 == 1 is True. Second, the range is finite. exp(710) is already inf in float64, and exp(89) is inf in float32.

The condition number of a problem

Rounding errors are tiny. Whether they matter depends on the problem. Take the system

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

Change the last entry of the right-hand side to 2.00022.0002, and the solution jumps to x=(0,2)x = (0, 2). The data changed by 3.5⋅10−53.5 \cdot 10^{-5} in relative terms, the answer by 100%100\%: an amplification of about 28,00028{,}000. The two equations are nearly parallel lines, and their intersection slides far along them. No algorithm is to blame here. The problem itself is sensitive.

The condition number of a problem measures this sensitivity: the worst ratio of the relative change in the answer to the relative change in the data, for small changes. For a function of one variable it is

κf(x)=∣x f′(x)f(x)∣.\kappa_f(x) = \left\lvert \frac{x\, f'(x)}{f(x)} \right\rvert.

Three examples:

  • f(x)=xf(x) = \sqrt{x}: κ=12\kappa = \tfrac12 everywhere, so a square root halves relative errors.
  • f(x)=exf(x) = e^x: κ=∣x∣\kappa = \lvert x \rvert, so e100e^{100} is accurate only to about 100 εmach100\,\varepsilon_{\text{mach}}.
  • f(x)=x−1f(x) = x - 1: κ=∣x/(x−1)∣\kappa = \lvert x/(x - 1) \rvert, huge near x=1x = 1. At x=1.0000001x = 1.0000001 it is 10710^7. Float64 returns x−1=1.0000000005838672⋅10−7x - 1 = 1.0000000005838672 \cdot 10^{-7}, a relative error of 5.8⋅10−105.8 \cdot 10^{-10}, although the subtraction itself is exact. The error was made when xx was rounded.

Rounding the input alone perturbs it by up to 12εmach\tfrac12\varepsilon_{\text{mach}}. Even a perfect algorithm then returns an answer off by about κ εmach\kappa\,\varepsilon_{\text{mach}}. The rule of thumb: a problem with condition number κ\kappa loses about log⁡10κ\log_{10}\kappa decimal digits.

The condition number of a matrix

For a linear system Ax=bAx = b with invertible AA, the condition number is a property of the matrix. A change δb\delta b in the data moves the solution by δx=A−1δb\delta x = A^{-1}\delta b, so ∥δx∥≤∥A−1∥ ∥δb∥\lVert \delta x \rVert \le \lVert A^{-1} \rVert\,\lVert \delta b \rVert. Divide by ∥x∥\lVert x \rVert and use 1/∥x∥≤∥A∥/∥b∥1/\lVert x \rVert \le \lVert A \rVert / \lVert b \rVert, which follows from ∥b∥=∥Ax∥≤∥A∥ ∥x∥\lVert b \rVert = \lVert Ax \rVert \le \lVert A \rVert\,\lVert x \rVert:

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

Here ∥A∥\lVert A \rVert is the largest stretch σmax⁡\sigma_{\max}, and A−1A^{-1} stretches by at most 1/σmin⁡1/\sigma_{\min}, with the singular values from the topic The singular value decomposition. The matrix of the previous block has σmax⁡=2.00005\sigma_{\max} = 2.00005 and σmin⁡=0.00005\sigma_{\min} = 0.00005, so κ(A)≈4⋅104\kappa(A) \approx 4 \cdot 10^4. The amplification of 28,00028{,}000 we saw stays under this bound.

Two extremes are worth remembering. An orthogonal matrix has all singular values equal to 11 and κ=1\kappa = 1: it rotates and reflects without distorting. A singular matrix has σmin⁡=0\sigma_{\min} = 0 and κ=∞\kappa = \infty.

Good solvers, such as LU with pivoting from Matrices and linear systems, Cholesky and QR, are backward stable: the computed x^\hat x is the exact solution of a slightly perturbed system, with relative perturbations of order εmach\varepsilon_{\text{mach}}. Combined with the bound above, their relative error is about κ(A) εmach\kappa(A)\,\varepsilon_{\text{mach}}, and no algorithm can promise more. The Hilbert matrix Hij=1/(i+j−1)H_{ij} = 1/(i + j - 1) shows how fast this bites. Here is np.linalg.solve on Hx=H1Hx = H\mathbf 1 in float64, whose exact answer is the vector of ones:

nn κ(H)\kappa(H) Relative error of x^\hat x
55 4.8⋅1054.8 \cdot 10^5 1⋅10−111 \cdot 10^{-11}
1010 1.6⋅10131.6 \cdot 10^{13} 3⋅10−43 \cdot 10^{-4}
1313 5.7⋅10175.7 \cdot 10^{17} 88, that is 800%800\%

The residual ∥b−Hx^∥/∥b∥\lVert b - H\hat x \rVert / \lVert b \rVert stays near 10−1610^{-16} in every row. A small residual is a small backward error. With r=b−Hx^r = b - H\hat x, the matrix ΔH=rx^⊤/∥x^∥2\Delta H = 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, and its norm is ∥r∥/∥x^∥\lVert r \rVert / \lVert \hat x \rVert, about 10−16 ∥H∥10^{-16}\,\lVert H \rVert here. So x^\hat x is the exact solution of a system that differs from ours in the sixteenth digit. The algorithm did its job; the error comes from κ(H)\kappa(H). A small residual does not say x^\hat x is accurate.

Least squares: QR, not the normal equations

Least squares from Inner products, norms and orthogonality has two textbook routes. The normal equations X⊤Xw=X⊤yX^\top X w = X^\top y are short to write. The QR route factors X=QRX = QR and solves Rw=Q⊤yRw = Q^\top y. With the SVD X=UΣV⊤X = U \Sigma V^\top the difference between them takes one line:

X⊤X=VΣ2V⊤⟹κ(X⊤X)=κ(X)2.X^\top X = V \Sigma^2 V^\top \quad\Longrightarrow\quad \kappa(X^\top X) = \kappa(X)^2.

Forming X⊤XX^\top X squares the condition number before any solver sees it. Even a backward-stable solver then loses about 2log⁡10κ(X)2\log_{10}\kappa(X) digits. QR squares nothing. QQ only rotates, so RR has the same singular values as XX, and the loss is about log⁡10κ(X)\log_{10}\kappa(X) digits when the model fits the data closely. (With a large residual the least-squares problem itself gains a term κ2tan⁡θ\kappa^2\tan\theta, where θ\theta is the angle between yy and the column space of XX. QR pays it too, but it vanishes for an exact fit, while the normal equations pay κ2\kappa^2 always.)

An experiment: 100×6100 \times 6 design matrices with a prescribed κ(X)\kappa(X), true weights w=(1,…,1)w = (1, \dots, 1), exact targets y=Xwy = Xw, float64, median relative error of ww over 2020 random matrices:

κ(X)\kappa(X) Normal equations QR lstsq (SVD)
10310^3 2⋅10−112 \cdot 10^{-11} 9⋅10−159 \cdot 10^{-15} 9⋅10−159 \cdot 10^{-15}
10610^6 2⋅10−52 \cdot 10^{-5} 4⋅10−124 \cdot 10^{-12} 3⋅10−123 \cdot 10^{-12}
10810^8 0.170.17 5⋅10−105 \cdot 10^{-10} 3⋅10−103 \cdot 10^{-10}

At κ(X)=108\kappa(X) = 10^8, a common sight with polynomial features or nearly duplicated columns, the normal equations keep barely one digit, while QR keeps about nine.

The rule for code: (X⊤X)−1X⊤y(X^\top X)^{-1} X^\top y belongs in derivations. Programs call np.linalg.lstsq or a QR-based solver and never form an explicit inverse.

Log-sum-exp and a stable softmax

Classification losses are full of exponentials. Softmax turns logits z∈RKz \in \mathbb R^K into probabilities, and the cross-entropy needs the log-sum-exp:

softmax⁡(z)i=ezi∑jezj,lse⁡(z)=log⁡∑jezj.\operatorname{softmax}(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}}, \qquad \operatorname{lse}(z) = \log \sum_j e^{z_j}.

Written this way, they break at moderate sizes. For z=(1000,999,998)z = (1000, 999, 998) float64 computes e1000=∞e^{1000} = \infty, so lse returns ∞\infty, and softmax divides ∞\infty by ∞\infty and returns nan. In float32 logits above 88.788.7 are enough to overflow, in float16 above 11.111.1.

The fix uses a property of softmax: adding the same constant cc to every logit changes nothing, because ece^{c} cancels between the numerator and the denominator. For lse the constant simply comes out: lse⁡(z+c)=lse⁡(z)+c\operatorname{lse}(z + c) = \operatorname{lse}(z) + c. Take c=−mc = -m with m=max⁡jzjm = \max_j z_j:

lse⁡(z)=m+log⁡∑jezj−m,softmax⁡(z)i=ezi−m∑jezj−m.\operatorname{lse}(z) = m + \log \sum_j e^{z_j - m}, \qquad \operatorname{softmax}(z)_i = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}}.

Now every exponent is at most 00, so nothing overflows. The largest term equals 11, so the sum cannot vanish either, and m≤lse⁡(z)≤m+log⁡Km \le \operatorname{lse}(z) \le m + \log K. For the example, lse⁡(z)=1000.4076\operatorname{lse}(z) = 1000.4076 and the probabilities are (0.665,0.245,0.090)(0.665, 0.245, 0.090).

The same idea rescues the softplus log⁡(1+et)\log(1 + e^t) inside the logistic loss:

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

At t=800t = 800 the naive formula gives ∞\infty and the stable one gives 800800. At t=−40t = -40 the naive formula gives 00, because 1+4.2⋅10−181 + 4.2 \cdot 10^{-18} rounds to 11; the stable one gives 4.25⋅10−184.25 \cdot 10^{-18}. This is why frameworks provide log_softmax and cross-entropy that takes logits, and why they beat log(softmax(z)).

Catastrophic cancellation

Subtraction is the operation that turns small input errors into large output errors. If a^\hat a and b^\hat b carry relative errors up to ε\varepsilon, then

∣(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}.

When a≈ba \approx b the factor is huge. The leading digits cancel, and the rounding noise in the trailing digits becomes the answer. This is catastrophic cancellation, the general form of the x−1x - 1 example from the second block.

Take (1−cos⁡x)/x2(1 - \cos x)/x^2, which tends to 12\tfrac12 as x→0x \to 0. The identity 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2) gives a version without subtraction. In float64:

xx (1−cos⁡x)/x2(1 - \cos x)/x^2 2sin⁡2(x/2)/x22\sin^2(x/2)/x^2
10−410^{-4} 0.49999999700.4999999970 0.49999999960.4999999996
10−610^{-6} 0.50004450.5000445 0.50000000000.5000000000
10−810^{-8} 00 0.50000000000.5000000000

At x=10−8x = 10^{-8} the cosine rounds to exactly 11, and all information is gone. This time the problem is not to blame. Near 00 the function is 12−x2/24+…\tfrac12 - x^2/24 + \dots, so κf≈x2/6\kappa_f \approx x^2/6, which is tiny. The formula is to blame: the rounding error of cos⁡x\cos x, up to 12εmach\tfrac12\varepsilon_{\text{mach}}, meets the subtraction factor (1+cos⁡x)/(1−cos⁡x)≈4/x2(1 + \cos x)/(1 - \cos x) \approx 4/x^2. An algorithm that loses far more than κf εmach\kappa_f\,\varepsilon_{\text{mach}} is unstable, and the rewrite makes it stable.

An ML example: batch normalization needs the variance of activations. The one-pass formula E[x2]−(E[x])2\mathbb E[x^2] - (\mathbb E[x])^2 subtracts two large, nearly equal numbers. For the float32 values 1000110001, 1000210002, 1000310003 it returns −4-4 instead of 23\tfrac23, and the square root of the variance becomes nan. The two-pass formula subtracts the mean first and then averages the squares; it returns 0.66670.6667. Finite-difference gradients suffer the same way: (f(x+h)−f(x))/h(f(x + h) - f(x))/h gets worse, not better, once hh is too small.

The recipe: when two nearly equal quantities are about to be subtracted, look for an algebraic rewrite that does the subtraction exactly or not at all.

Ill-conditioned optimization

The condition number also met us in Unconstrained optimization. On a quadratic loss with Hessian HH, gradient descent with the best fixed step shrinks the error by a factor of (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) per step, where κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}. The step must stay below 2/λmax⁡2/\lambda_{\max}, so the flat direction with curvature λmin⁡\lambda_{\min} crawls, and the number of steps grows in proportion to κ\kappa.

Floating point makes flat directions worse still. In a flat direction the update η ∂L/∂θi\eta\, \partial L/\partial \theta_i is small, and if it falls below half the gap between neighbouring numbers, it is rounded away. In bfloat16, 1+0.0031 + 0.003 rounds back to 11. This is why mixed precision training runs the forward and backward passes in bfloat16 or float16, but keeps a float32 copy of the weights and adds the updates there.

Two standard remedies attack κ\kappa itself.

Preconditioning changes variables, θ=Pθ′\theta = P\theta', so that the Hessian in the new coordinates, P⊤HPP^\top H P, is closer to II. Newton's method is the extreme case P=H−1/2P = H^{-1/2}. Adam's per-coordinate step sizes and normalization layers are cheap approximations.

Weight decay adds λ2∥θ∥2\tfrac{\lambda}{2}\lVert\theta\rVert^2 to the loss, and with it λI\lambda I to the Hessian. Every eigenvalue grows by λ\lambda:

κ(H+λI)=λmax⁡+λλmin⁡+λ.\kappa(H + \lambda I) = \frac{\lambda_{\max} + \lambda}{\lambda_{\min} + \lambda}.

The same shift is ridge regression in least squares and the small "jitter" added to kernel matrices before a Cholesky factorization.

One cost has stayed in the background. The good solvers of this topic, LU, Cholesky and QR, are backward stable, but each of them factors the matrix first: O(n3)O(n^3) operations and n2n^2 stored numbers for an n×nn \times n matrix. At n=106n = 10^6 that is out of reach, and the Hessian of a large network is never even written down. Yet a product v↦Avv \mapsto Av is often cheap. Methods that touch AA only through such products are the next and last topic, Iterative methods: power iteration and conjugate gradient.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Log-sum-exp in codeoptional

    Implement a numerically stable log-sum-exp — the backbone of stable softmax.

    ~15 min · easier on a computer · The Conditioning and numerical stability topic, log-sum-exp block.

    Open practice

Full notes

Answers are saved on the server and tied to this browser until you sign in.