Module contents
Lesson 3 of 26Core 90 min

Conditioning, stability and backward error analysis

Distinguish intrinsically sensitive problems from unstable algorithms through condition numbers, forward and backward errors and linear-system diagnostics.

After this lesson you can

  • Calculate relative condition numbers for scalar functions and simple vector problems.
  • Distinguish forward and backward errors and compute normwise backward error for Ax = b.
  • Use the forward error ≲ κ · backward error rule to predict correct digits.
  • Classify algorithms as backward stable, stable or unstable using examples.
  • Diagnose whether a poor result comes from the problem or the algorithm.

Before you start

Motivation: two programs, two answers

Fit a degree-12 polynomial to 60 points of a noisy sinusoid. This is linear regression: seek c∈R13\vb{c} \in \R^{13} minimizing ∥Xc−y∥2\norm{\mat{X}\vb{c} - \vb{y}}_2, with X\mat{X} the points’ Vandermonde matrix. A colleague solves it with normal equations, X⊤Xc=X⊤y\mat{X}\T\mat{X}\vb{c} = \mat{X}\T\vb{y}, and you with np.linalg.lstsq. Both programs are correct in exact arithmetic and finish without warnings.

[ ]Two programs, two answersBrowser
import numpy as np

rng = np.random.default_rng(0)
t = np.linspace(0, 1, 60)
y = np.sin(2 * np.pi * t) + 0.01 * rng.standard_normal(60)
X = np.vander(t, 13, increasing=True)          # columnas 1, t, t^2, ..., t^12

c_ne = np.linalg.solve(X.T @ X, X.T @ y)          # ecuaciones normales
c_ls = np.linalg.lstsq(X, y, rcond=None)[0]       # QR/SVD de LAPACK

np.set_printoptions(precision=6, suppress=False)
print("ecuaciones normales, c[:4] =", c_ne[:4])
print("lstsq,               c[:4] =", c_ls[:4])
print(f"diferencia relativa de los coeficientes:   {np.linalg.norm(c_ne - c_ls) / np.linalg.norm(c_ls):.2e}")
print(f"diferencia relativa de las predicciones:   {np.linalg.norm(X @ c_ne - X @ c_ls) / np.linalg.norm(X @ c_ls):.2e}")
print(f"norma del residuo: {np.linalg.norm(X @ c_ne - y):.10f} frente a {np.linalg.norm(X @ c_ls - y):.10f}")

The coefficients do not even agree in the first digit: the third is 32.732.7 in one case and 25.025.0 in the other, the fourth −525-525 and −391-391, and the relative difference between vectors is 119%. Yet fitted curves differ by only 4 ten-thousandths relatively and residual norms agree to three digits. Which is right? Is either? Two distinct questions are mixed together, and separating them is this lesson’s goal:

  1. Is the problem sensitive? If data change slightly (as they always do: storing in float64 already rounds them), does the exact answer change much? That is conditioning, a property of the problem independent of any algorithm.
  2. Is the algorithm good? Does it add errors not justified by the problem? That is stability, a property of the algorithm.

A poor result can come from either, and the remedies differ: no algorithm fixes an ill-conditioned problem (change the problem, data or precision), while an unstable algorithm can be replaced. At the end you will return to this regression and identify what happened and how many digits of each answer can be trusted.

A problem’s condition number

A problem is a function f:X→Yf: X \to Y between normed spaces (in practice open subsets of Rn\R^n and Rm\R^m) mapping data x\vb{x} to solution y=f(x)\vb{y} = f(\vb{x}). Subtracting two numbers is problem f(x1,x2)=x1−x2f(x_1, x_2) = x_1 - x_2; solving a system is f(A,b)=A−1bf(\mat{A}, \vb{b}) = \mat{A}\inv\vb{b}; polynomial roots are a function of coefficients. Conditioning asks a purely mathematical question: if x\vb{x} moves slightly, how much does f(x)f(\vb{x}) move?

κ\kappa is the worst-case factor by which the problem multiplies infinitesimal relative data errors. Two aspects matter: the supremum (worst case over all perturbation directions) and limit (a first-order notion valid for small perturbations). If ff is differentiable at x\vb{x} with Jacobian J(x)\mat{J}(\vb{x}), then f(x+δx)−f(x)=J(x) δx+o(∥δx∥)f(\vb{x} + \delta\vb{x}) - f(\vb{x}) = \mat{J}(\vb{x})\,\delta\vb{x} + o(\norm{\delta\vb{x}}), and the supremum of ratio ∥Jδx∥/∥δx∥\norm{\mat{J}\delta\vb{x}}/\norm{\delta\vb{x}} is by definition the operator norm of J\mat{J}:

κ^(x)=∥J(x)∥,κ(x)=∥J(x)∥ ∥x∥∥f(x)∥.\hat\kappa(\vb{x}) = \norm{\mat{J}(\vb{x})}, \qquad \kappa(\vb{x}) = \frac{\norm{\mat{J}(\vb{x})}\,\norm{\vb{x}}}{\norm{f(\vb{x})}}.

In the scalar case, with ff differentiable at xx, the most frequently used formula is:

κ(x)=∣x f′(x)f(x)∣=∣ ⁣dlog⁡∣f∣ ⁣dlog⁡∣x∣∣.\kappa(x) = \abs{\frac{x\,f'(x)}{f(x)}} = \abs{\frac{\dd \log\abs{f}}{\dd \log\abs{x}}}.

The second form says what κ\kappa measures: the elasticity of ff, the percentage output change per one-percent data change. It also has a useful decimal-digit interpretation: relative data error 10−s10^{-s} (data have ss correct digits) gives relative solution error up to κ⋅10−s\kappa\cdot 10^{-s}, with s−log⁡10κs - \log_{10}\kappa correct digits. A problem with condition number κ\kappa consumes about log⁡10κ\log_{10}\kappa digits, whatever the algorithm. Use vector norms appropriate to the problem; changing norm changes κ\kappa by at most a factor depending on dimension, not data.

InteractiveThe conditioning magnifier
relative output width / δ = 8.913
log⁡10κ\log_{10}\kappa throughout the domain: digits lost at each point
10⁰10¹10²10³≥ 10⁴
  • perturbed input x(1±δ)x(1 \pm \delta)
  • image of interval
  • region with κ>10\kappa > 10
1.1200
0.02
Problemf(x)=log⁡xf(x) = \log x
Formulaκ(x)=1∣log⁡x∣\kappa(x) = \dfrac{1}{\abs{\log x}}
κ\kappa at input8.824
Measured amplification with δ\delta8.913
Digits lost ≈log⁡10κ\approx \log_{10}\kappa0.9
Near x=1x = 1 the result is nearly zero and any relative input error is amplified.
The blue band is the data interval [x(1−δ),x(1+δ)][x(1 - \delta), x(1 + \delta)], with the same relative width δ\delta wherever xx lies; magenta is its image under ff. “Measured amplification” divides relative image width by δ\delta, without derivatives, and for small δ\delta agrees with κ(x)\kappa(x). Below is log⁡10κ\log_{10}\kappa over the domain. Drag xx toward 1 with logarithm and x−1x - 1, toward π/2\pi/2 with tangent and toward c=1c = 1 with the root. With x\sqrt{x}, try to find a dangerous region.

Four examples worth remembering

Subtracting nearby numbers. For f(x1,x2)=x1−x2f(x_1, x_2) = x_1 - x_2 with data norm ∥⋅∥∞\norm{\cdot}_\infty, the Jacobian is J=[1  −1]\mat{J} = [1\ \ {-1}], with norm ∥J∥∞=2\norm{\mat{J}}_\infty = 2 (as a mapping from (R2,∥⋅∥∞)(\R^2, \norm{\cdot}_\infty) to R\R), so

κ(x1,x2)=2max⁡(∣x1∣,∣x2∣)∣x1−x2∣.\kappa(x_1, x_2) = \frac{2\max(\abs{x_1}, \abs{x_2})}{\abs{x_1 - x_2}}.

If each datum carries its own relative error, ∣δxi∣≤ε∣xi∣\abs{\delta x_i} \le \eps\abs{x_i} (as when rounding), componentwise calculation gives (∣x1∣+∣x2∣)/∣x1−x2∣(\abs{x_1} + \abs{x_2})/\abs{x_1 - x_2}. In both versions, subtracting numbers agreeing in their first kk digits has κ≈10k\kappa \approx 10^k. This is precisely the previous lesson’s catastrophic cancellation viewed differently: subtraction introduces no error (floating-point subtraction of nearby numbers is even exact by Sterbenz’s lemma), but reveals errors already present in the operands, amplified by κ\kappa. The interactive shows this with f(x)=x−1f(x) = x - 1: κ=∣x∣/∣x−1∣\kappa = \abs{x}/\abs{x - 1}, which explodes at x=1x = 1.

Logarithm near 1. With f(x)=log⁡xf(x) = \log x, κ(x)=∣x⋅(1/x)/log⁡x∣=1/∣log⁡x∣\kappa(x) = \abs{x \cdot (1/x)/\log x} = 1/\abs{\log x}. Away from x=1x = 1 it is moderate, but at x=1+sx = 1 + s with small ss, log⁡x≈s\log x \approx s and κ≈1/s\kappa \approx 1/s: datum x=1.0001x = 1.0001 has κ≈104\kappa \approx 10^4. Notice the subtlety: ill-conditioning depends on what is considered the data. If s=x−1s = x - 1 is known accurately (for example, a small financial return), the problem is g(s)=log⁡(1+s)g(s) = \log(1 + s), with κ(s)=∣s/((1+s)log⁡(1+s))∣≈1\kappa(s) = \abs{s/((1 + s)\log(1 + s))} \approx 1. Computing np.log(1 + s) turns a well-conditioned problem into an ill-conditioned one by forming 1+s1 + s, discarding the last digits of ss; np.log1p(s) directly solves the well-conditioned problem. This is one of the previous lesson’s stable reformulations.

Tangent near π/2\pi/2. κ(x)=∣x (1+tan⁡2x)/tan⁡x∣=∣x/(sin⁡xcos⁡x)∣=2∣x∣/∣sin⁡2x∣\kappa(x) = \abs{x\,(1 + \tan^2 x)/\tan x} = \abs{x/(\sin x\cos x)} = 2\abs{x}/\abs{\sin 2x}. It explodes at poles (x→π/2x \to \pi/2, where tan⁡x→∞\tan x \to \infty) and at zeros with x≠0x \neq 0 (x→πx \to \pi): at x=1.57x = 1.57, κ≈1972\kappa \approx 1972. Since π/2\pi/2 is not a machine number, np.tan(np.pi / 2) returns 1.6×10161.6\times 10^{16} rather than infinity: stored input is distance 6×10−176\times 10^{-17} from the pole. Its tangent is computed accurately, but there κ≈2.6×1016\kappa \approx 2.6\times 10^{16}, so representation error of 4×10−174\times 10^{-17} relatively suffices to make the result unrelated to the intended value.

Polynomial roots. Let rr be a simple root of p(x)=∑i=0naixip(x) = \sum_{i=0}^{n} a_i x^i, i.e. p(r)=0p(r) = 0 and p′(r)≠0p'(r) \neq 0. Consider rr as a function of coefficient aja_j. Differentiating identity p(r(aj);aj)=0p(r(a_j); a_j) = 0 with respect to aja_j (justified by the implicit function theorem, because ∂p/∂x=p′(r)≠0\partial p/\partial x = p'(r) \neq 0),

p′(r) ∂r∂aj+rj=0⟹∂r∂aj=−rjp′(r),κj(r)=∣ajr⋅rjp′(r)∣=∣aj rj−1∣∣p′(r)∣.p'(r)\,\frac{\partial r}{\partial a_j} + r^j = 0 \quad\Longrightarrow\quad \frac{\partial r}{\partial a_j} = -\frac{r^j}{p'(r)}, \qquad \kappa_j(r) = \abs{\frac{a_j}{r}\cdot\frac{r^j}{p'(r)}} = \frac{\abs{a_j\,r^{j-1}}}{\abs{p'(r)}}.

At a double root, p′(r)=0p'(r) = 0 and κ=∞\kappa = \infty: the interactive shows this with the larger root of x2−2x+cx^2 - 2x + c, equal to 1+1−c1 + \sqrt{1 - c} and colliding with the other at c=1c = 1. But a double root is not necessary for ill-conditioning, as Wilkinson discovered.

Wilkinson’s polynomial

In the late 1950s James H. Wilkinson tested his root programs with the most innocent polynomial he could devise, w(x)=(x−1)(x−2)⋯(x−20)w(x) = (x - 1)(x - 2)\cdots(x - 20), and obtained disastrous results. The preceding formula explains why. Roots are k=1,…,20k = 1, \dots, 20, all simple and separated by 1, with ∣w′(k)∣=∏j≠k∣k−j∣=(k−1)! (20−k)!\abs{w'(k)} = \prod_{j \neq k}\abs{k - j} = (k - 1)!\,(20 - k)!. The coefficient of x19x^{19} is a19=−(1+2+⋯+20)=−210a_{19} = -(1 + 2 + \cdots + 20) = -210, so the condition number of root kk with respect to it is

κ19(k)=210 k18(k−1)! (20−k)!.\kappa_{19}(k) = \frac{210\,k^{18}}{(k - 1)!\,(20 - k)!}.
[ ]Conditioning of Wilkinson rootsBrowser
from math import factorial, prod
from fractions import Fraction

# coeficientes exactos de w(x) = (x-1)(x-2)...(x-20), de mayor a menor grado
a = [1]
for k in range(1, 21):
    a = [x - k * y for x, y in zip(a + [0], [0] + a)]
coef = {20 - i: c for i, c in enumerate(a)}       # coef[j] = a_j, coeficiente de x^j
print("a_19 =", coef[19], "   a_0 = 20! =", coef[0])

def dw(k):                                        # w'(k) = prod_{j != k} (k - j)
    return prod(k - j for j in range(1, 21) if j != k)

def kappa(k, j):                                  # condición de la raíz k respecto a a_j
    return float(abs(coef[j]) * Fraction(k) ** (j - 1) / abs(dw(k)))

for k in [1, 5, 10, 14, 15, 16, 20]:
    print(f"raíz {k:2d}:  kappa respecto a a_19 = {kappa(k, 19):9.3e}   "
          f"desplazamiento lineal con eps = 2^-23: {2.0**-23 * k**19 / abs(dw(k)):9.3e}")

peor = max((kappa(k, j), k, j) for k in range(1, 21) for j in range(20) if coef[j] != 0)
print(f"\nla peor: raíz {peor[1]} respecto a a_{peor[2]}, kappa = {peor[0]:.3e}")

Root 16 has κ19≈3.2×1010\kappa_{19} \approx 3.2\times 10^{10}, and the worst combination (root 14 relative to coefficient a12a_{12}) reaches 101310^{13}. Thus rounding coefficients to float64, with relative error u≈1.1×10−16u \approx 1.1\times 10^{-16}, can already move some roots in their third digit. Wilkinson made the definitive experiment: he changed a19a_{19} from −210-210 to −210−2−23-210 - 2^{-23}, a relative change of 5.7×10−105.7\times 10^{-10}.

[ ]Perturbed polynomial roots to 40 digitsBrowser
import mpmath as mp

mp.mp.dps = 40                                   # 40 cifras: los coeficientes llegan a 10^19 y el cambio relativo es 6e-10
c = [mp.mpf(v) for v in a]                       # a[0] es el coeficiente de x^20
c[1] -= mp.mpf(2) ** -23                         # -210 - 2^-23
raices = sorted(mp.polyroots(c, maxsteps=100, extraprec=60), key=lambda z: (float(z.real), float(z.imag)))
for z in raices:
    print(f"{float(z.real):10.6f} {float(z.imag):+10.6f}i")

# ¿desde qué tamaño de perturbación dejan de ser reales algunas raíces?
for eps in (1e-10, 2e-10):
    c = [mp.mpf(v) for v in a]
    c[1] -= mp.mpf(eps)
    r = mp.polyroots(c, maxsteps=100, extraprec=60)
    complejas = sorted(float(z.real) for z in r if abs(z.imag) > 1e-20)
    print(f"eps = {eps:.0e}: {len(complejas)} raíces no reales, con partes reales", [round(v, 2) for v in complejas])

Ten of the twenty roots have become five complex pairs, and the furthest pair, 16.730737±2.812625 i16.730737 \pm 2.812625\,i, is almost 3 units from original roots 16 and 17. Linear prediction 2−23⋅1619/∣w′(16)∣≈2872^{-23}\cdot 16^{19}/\abs{w'(16)} \approx 287 is useless here: displacement is so large that the first-order approximation ceased to hold much earlier. The condition number describes behavior for infinitesimal perturbations; when κ⋅ε\kappa\cdot\eps is no longer small, it only says the problem is lost.

InteractiveWilkinson's roots scatter
Complex plane with the 20 roots of pε(x)=(x−1)⋯(x−20)−εx19p_\varepsilon(x) = (x - 1)\cdots(x - 20) - \varepsilon x^{19} and their paths from ε=10−14\varepsilon = 10^{-14}. Your browser computes them using Aberth's method evaluating pεp_\varepsilon in product form without coefficients (at ε=2−23\varepsilon = 2^{-23} they reproduce the previous cell's 40-digit values). Lower ε\varepsilon until all roots are real again, then raise it slowly: which collide first? Follow root 16 and compare actual displacement with linear prediction εk19/∣p′(k)∣\varepsilon k^{19}/\abs{p'(k)}: they agree while ε\varepsilon is small and diverge later.

The slider reveals the critical order of magnitude: the first real roots collide and leave the axis at ε≈2×10−10\varepsilon \approx 2\times 10^{-10}, long before 2−23≈1.2×10−72^{-23} \approx 1.2\times 10^{-7}. The first collisions are center-right (around 14 to 17), precisely those with largest κ19\kappa_{19}. Wilkinson’s lesson in “The perfidious polynomial” (1984) is twofold. An innocent-looking problem can be terribly conditioned. Representation matters: the same set of numbers {1,…,20}\{1, \dots, 20\}, seen as eigenvalues of symmetric matrix diag⁡(1,…,20)\diag(1, \dots, 20), is perfectly stable: perturbing the matrix with E\mat{E} moves each eigenvalue by at most ∥E∥2\norm{\mat{E}}_2, so its absolute condition number is 1 (see eigenvalue sensitivity). Going through characteristic-polynomial coefficients unnecessarily chooses an ill-conditioned intermediate problem.

Forward error, backward error

Now the algorithm. Instead of ff, the computer evaluates function f~\tilde f (the floating-point program) and obtains y^=f~(x)\hat{\vb{y}} = \tilde f(\vb{x}). There are two ways to measure its error.

x→  f  y=f(x)↓error hacia atraˊs↕error hacia delantex+Δx→  f  y^=f~(x)=f(x+Δx)\begin{array}{ccc} \vb{x} & \xrightarrow{\ \ f\ \ } & \vb{y} = f(\vb{x}) \\[2pt] \big\downarrow{\scriptstyle\text{error hacia atrás}} & & \big\updownarrow{\scriptstyle\text{error hacia delante}} \\[2pt] \vb{x} + \Delta\vb{x} & \xrightarrow{\ \ f\ \ } & \hat{\vb{y}} = \tilde f(\vb{x}) = f(\vb{x} + \Delta\vb{x}) \end{array}

Forward error is what you would like to know, but requires the exact answer. Backward error answers another question: for which data is y^\hat{\vb{y}} the exact answer? If those data are distance 10−1610^{-16} from yours, and your data already carried measurement or rounding errors of that size, y^\hat{\vb{y}} is as good as any answer you can justify. This idea, turned into a method by Wilkinson in the 1950s and 1960s, made linear-algebra algorithm analysis possible: backward error is almost always easier to bound than forward error.

One example of each type, with the standard model fl⁡(a∘b)=(a∘b)(1+δ)\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta), ∣δ∣≤u\abs{\delta} \le u, where u=2−53≈1.1×10−16u = 2^{-53} \approx 1.1\times 10^{-16} is float64’s unit roundoff:

  • Square root. y^=fl⁡(x)=x (1+δ)\hat y = \operatorname{fl}(\sqrt{x}) = \sqrt{x}\,(1 + \delta). Relative forward error: ∣δ∣≤u\abs{\delta} \le u. Backward error: y^=x(1+δ)2\hat y = \sqrt{x(1 + \delta)^2}, so y^\hat y is the exact root of x(1+δ)2x(1 + \delta)^2 and η≤2u+u2\eta \le 2u + u^2. Both are small.
  • Adding 1 to a tiny number. With x=10−20x = 10^{-20}, fl⁡(x+1)=1\operatorname{fl}(x + 1) = 1. Relative forward error is 10−2010^{-20}, tiny. But the only datum giving exactly 1 is x~=0\tilde x = 0, at relative distance ∣0−x∣/∣x∣=1\abs{0 - x}/\abs{x} = 1: 100% backward error. The result is excellent yet is not the exact answer for any nearby datum.

Algorithm stability

The second example shows that “small backward error” is a strong requirement, stronger than “good result.” This leads to two quality levels. Below, O(u)\bigO(u) means “bounded by C uC\,u with constant CC that may depend on problem dimension but not datum x\vb{x}.”

Backward stable implies stable (take the same x~\tilde{\vb{x}} and zero output error). Higham also uses a weaker third notion: an algorithm is forward stable if its forward error has the same order as a backward-stable one, O(κu)\bigO(\kappa u), even if backward error is not small. Neither definition promises small forward error: a backward-stable algorithm applied to an ill-conditioned problem produces large error without ceasing to be an excellent algorithm. This is the best one can ask: if data already have errors of size uu, error from a backward-stable algorithm is indistinguishable from that of the data themselves.

Examples worth classifying:

  • Floating-point subtraction (and addition) is backward stable. fl⁡(x1−x2)=(x1−x2)(1+δ)=x1(1+δ)−x2(1+δ)\operatorname{fl}(x_1 - x_2) = (x_1 - x_2)(1 + \delta) = x_1(1 + \delta) - x_2(1 + \delta): it is exact subtraction of two data relatively perturbed by ∣δ∣≤u\abs{\delta} \le u. If data arrive rounded, xi(1+εi)x_i(1 + \eps_i), total perturbation is below 2u+u22u + u^2. Yet the result may have no correct digits: subtraction is not at fault; the problem has κ=(∣x1∣+∣x2∣)/∣x1−x2∣\kappa = (\abs{x_1} + \abs{x_2})/\abs{x_1 - x_2}.
  • The dot product is backward stable. Summing left to right, fl⁡(x⊤y)=∑ixiyi(1+θi)\operatorname{fl}(\vb{x}\T\vb{y}) = \sum_i x_i y_i(1 + \theta_i) with ∣θi∣≤γn=nu/(1−nu)\abs{\theta_i} \le \gamma_n = nu/(1 - nu) (if nu<1nu < 1): it is the exact dot product of y\vb{y} and perturbed vector x~i=xi(1+θi)\tilde x_i = x_i(1 + \theta_i).
  • Outer product xy⊤\vb{x}\vb{y}\T is stable but not backward stable. Each entry has relative error ≤u\le u, so it is stable. But the computed matrix with entries xiyj(1+δij)x_i y_j(1 + \delta_{ij}) almost never has rank 1, and thus is not x~y~⊤\tilde{\vb{x}}\tilde{\vb{y}}\T for any vector pair: no nearby input makes it exact.
  • Floating-point x↦x+1x \mapsto x + 1 is stable but not backward stable, by the earlier example: x~=x+δ(x+1)\tilde x = x + \delta(x + 1) has relative error ∣δ(x+1)/x∣\abs{\delta(x + 1)/x}, unbounded as x→0x \to 0.
  • Gaussian elimination with partial pivoting, Householder QR and Cholesky are backward stable for linear systems (the first subject to its growth factor, usually small in practice). The next lesson’s elimination error analysis gives the proof.
  • Computing eigenvalues as roots of the characteristic polynomial is unstable: this is Wilkinson’s polynomial. So is the recurrence in “Unstable recurrences” below.
[ ]Stable is not the same as backward stableBrowser
import numpy as np
from fractions import Fraction

# x -> x + 1: resultado excelente, error hacia atrás del 100 %
x = 1e-20
y_hat = x + 1.0
exacto = Fraction(x) + 1                          # x + 1 sin redondear
print("fl(x + 1) =", y_hat, "  error relativo hacia delante:", float(abs(Fraction(y_hat) - exacto) / exacto))
print("único dato con (dato + 1) == 1 exactamente: 0, a distancia relativa", abs(0 - x) / abs(x))

# producto exterior: cada entrada exacta salvo u, pero la matriz no tiene rango 1
rng = np.random.default_rng(1)
u_, v_ = rng.standard_normal(6), rng.standard_normal(6)
M = np.outer(u_, v_)
s = np.linalg.svd(M, compute_uv=False)
print("\nvalores singulares del producto exterior calculado:", np.array2string(s, precision=2))
print("sigma_2 / sigma_1 =", s[1] / s[0], " (sería 0 si fuera exactamente de rango 1)")

The practical theorem: forward ≲κ\lesssim \kappa · backward

Conditioning and backward error combine in the most useful rule in numerical analysis. It follows directly from the definitions, and you will prove it in the final guided exercise.

This forward-error bound says forward error ≲\lesssim condition number × backward error, separating responsibilities: the problem supplies factor κ\kappa, the algorithm factor η\eta. For an algorithm that is merely stable, the same argument gives κ η+ε+O(η2)\kappa\,\eta + \eps + \bigO(\eta^2), where ε\eps is relative error added to output by the algorithm. In decimal digits, with a backward-stable float64 algorithm:

κ\kappaexpected correct digitsexample
11 to 101015 or 16x\sqrt{x}, log⁡x\log x away from 1, orthogonal systems
10410^4about 12log⁡(1.0001)\log(1.0001)
101010^{10}about 6Hilbert matrix 8×88\times 8
101610^{16} or morenoneHilbert matrix 12×1212\times 12

Diagnosis: the problem or the algorithm?

The theorem gives a procedure for the motivating case or any suspicious result:

  1. Estimate κ\kappa. If κ u\kappa\,u is comparable to observed error, the problem suffices to explain it.
  2. Measure backward error. Unlike forward error it can almost always be computed without knowing the exact solution (for linear systems, using the residual, as shown next).
  3. Decide. If η≈u\eta \approx u, the algorithm did its job and the problem is responsible: change the formulation, improve data or raise precision. If η≫u\eta \gg u, the algorithm is unstable for that input: replace it.

Linear systems

The central problem is f(A,b)=A−1bf(\mat{A}, \vb{b}) = \mat{A}\inv\vb{b} with invertible A\mat{A}. Its conditioning is known from matrix norms and conditioning: perturbing b\vb{b} relatively by ε\eps moves x\vb{x} by at most relative κ(A) ε\kappa(\mat{A})\,\eps, where κ(A)=∥A∥∥A−1∥\kappa(\mat{A}) = \norm{\mat{A}}\norm{\mat{A}\inv} is the matrix condition number, and the bound is attained. Perturbing both data simultaneously gives this linear-system sensitivity:

Proof

This is the perturbation theorem from matrix norms with ∥ΔA∥/∥A∥≤η\norm{\Delta\mat{A}}/\norm{\mat{A}} \le \eta and ∥Δb∥/∥b∥≤η\norm{\Delta\vb{b}}/\norm{\vb{b}} \le \eta: there it is shown that if κ∥ΔA∥/∥A∥<1\kappa\norm{\Delta\mat{A}}/\norm{\mat{A}} < 1, relative error is at most κ1−κ∥ΔA∥/∥A∥(∥ΔA∥/∥A∥+∥Δb∥/∥b∥)\frac{\kappa}{1 - \kappa\norm{\Delta\mat{A}}/\norm{\mat{A}}}\big(\norm{\Delta\mat{A}}/\norm{\mat{A}} + \norm{\Delta\vb{b}}/\norm{\vb{b}}\big), and each term is bounded by case η\eta.

∎

To first order, 2κη2\kappa\eta: factor 2 appears because two data are perturbed and is practically irrelevant. To use the theorem we still need η\eta for a particular solution x^\hat{\vb{x}}; the answer is exact and surprisingly simple.

Rigal and Gaches backward error

Proof

Equation (A+ΔA)x^=b+Δb(\mat{A} + \Delta\mat{A})\hat{\vb{x}} = \vb{b} + \Delta\vb{b} is equivalent to ΔA x^−Δb=r\Delta\mat{A}\,\hat{\vb{x}} - \Delta\vb{b} = \vb{r}.

Lower bound. If ΔA\Delta\mat{A} and Δb\Delta\vb{b} satisfy the equation with size ε\eps, then ∥r∥≤∥ΔA∥∥x^∥+∥Δb∥≤ε(∥A∥∥x^∥+∥b∥)\norm{\vb{r}} \le \norm{\Delta\mat{A}}\norm{\hat{\vb{x}}} + \norm{\Delta\vb{b}} \le \eps(\norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}}), i.e. ε≥∥r∥/(∥A∥∥x^∥+∥b∥)\eps \ge \norm{\vb{r}}/(\norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}}).

Attainment. Let D=∥A∥∥x^∥+∥b∥D = \norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}} and take a dual vector of x^\hat{\vb{x}}: an z\vb{z} with z⊤x^=∥x^∥\vb{z}\T\hat{\vb{x}} = \norm{\hat{\vb{x}}} and ∥z∥D=max⁡∥w∥=1∣z⊤w∣=1\norm{\vb{z}}_D = \max_{\norm{\vb{w}} = 1}\abs{\vb{z}\T\vb{w}} = 1 (in the 2-norm, z=x^/∥x^∥2\vb{z} = \hat{\vb{x}}/\norm{\hat{\vb{x}}}_2; in the ∞\infty norm, z=sign⁡(x^k) ek\vb{z} = \operatorname{sign}(\hat x_k)\,\vb{e}_k with kk the largest-component index; in general one exists by Hahn-Banach). Define

ΔA=∥A∥D r z⊤,Δb=−∥b∥D r.\Delta\mat{A} = \frac{\norm{\mat{A}}}{D}\,\vb{r}\,\vb{z}\T, \qquad \Delta\vb{b} = -\frac{\norm{\vb{b}}}{D}\,\vb{r}.

Then ΔA x^−Δb=∥A∥∥x^∥+∥b∥D r=r\Delta\mat{A}\,\hat{\vb{x}} - \Delta\vb{b} = \frac{\norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}}}{D}\,\vb{r} = \vb{r}. Since ∥rz⊤w∥=∣z⊤w∣ ∥r∥\norm{\vb{r}\vb{z}\T\vb{w}} = \abs{\vb{z}\T\vb{w}}\,\norm{\vb{r}}, the operator norm of rz⊤\vb{r}\vb{z}\T is ∥r∥ ∥z∥D=∥r∥\norm{\vb{r}}\,\norm{\vb{z}}_D = \norm{\vb{r}}, so ∥ΔA∥=∥r∥D∥A∥\norm{\Delta\mat{A}} = \frac{\norm{\vb{r}}}{D}\norm{\mat{A}} and ∥Δb∥=∥r∥D∥b∥\norm{\Delta\vb{b}} = \frac{\norm{\vb{r}}}{D}\norm{\vb{b}}: size exactly ε=∥r∥/D\eps = \norm{\vb{r}}/D.

∎

If only matrix perturbation is allowed (Δb=0\Delta\vb{b} = \vb{0}), the same argument gives ηA=∥r∥/(∥A∥∥x^∥)\eta_{\mat{A}} = \norm{\vb{r}}/(\norm{\mat{A}}\norm{\hat{\vb{x}}}), the relative residual, with ΔA=rx^⊤/∥x^∥22\Delta\mat{A} = \vb{r}\hat{\vb{x}}\T/\norm{\hat{\vb{x}}}_2^2 in 2-norm. The two differ by at most factor 2, because ∥b∥≤∥A∥∥x∥\norm{\vb{b}} \le \norm{\mat{A}}\norm{\vb{x}} and x^≈x\hat{\vb{x}} \approx \vb{x} unless all is lost.

The theorem has a major practical consequence: backward error of a linear-system solution is calculated with a matrix-vector product, without knowing the exact solution. It also has an equally large trap:

  • A small relative residual, η≈u\eta \approx u, certifies x^\hat{\vb{x}} as the exact solution of a system differing from yours at rounding level. It certifies stability, not accuracy.
  • Forward error can reach 2κ(A) η2\kappa(\mat{A})\,\eta. With κ=1012\kappa = 10^{12} and η=10−16\eta = 10^{-16}, the solution may have only 4 correct digits despite a “perfect” residual.
  • A large residual is a reliable alarm: if η≫u\eta \gg u, the algorithm did not behave backward stably on that input.
InteractiveForward versus backward error in 2×2
Each equation of Ax=b\mat{A}\vb{x} = \vb{b} is a line (unit normals at angle γ\gamma) and x\vb{x} their intersection. Data are rounded to chosen precision and each operation solving the system is rounded to it: this explicitly models arithmetic, not just a drawing. The red point is computed solution x^\hat{\vb{x}}; gray segments are residual components (distances from x^\hat{\vb{x}} to each line); dashed lines are Rigal-Gaches perturbed-data equations passing exactly through x^\hat{\vb{x}}; the blue ellipse is the set of points with backward error at most uu (to first order). The zoom fits x^\hat{\vb{x}} and the ellipse, with scale on the window label; global view shows full lines. Close γ\gamma: the ellipse elongates like κ\kappa and forward error grows, while dashed and solid lines barely separate. Then switch to Cramer's rule and inspect the blue sweep curve.

The interactive shows three things worth checking separately. With pivoted elimination, the backward-error curve remains flat below uu throughout the γ\gamma sweep and at all three precisions, while forward error rises with κu\kappa u: backward stability in action. Thus the computed point falls inside the ellipse of points with η≤u\eta \le u; that ellipse has semiaxes inversely proportional to singular values of A\mat{A}, so its length is κ\kappa times its width: the problem, not the algorithm, determines how far x^\hat{\vb{x}} can slide along the lines. With Cramer’s rule, forward error is the same order as elimination, but backward error grows with κ\kappa: in float16 with γ=0.5°\gamma = 0.5° (κ≈230\kappa \approx 230), η\eta reaches 7u7u versus 0.14u0.14u with elimination. Cramer in 2×22\times 2 is forward stable but not backward stable, Higham’s chapter 1 example.

Three algorithms, two clouds

For a larger system, the same diagnosis separates three practical behaviors. The next interactive solves 36 systems 6×66\times 6 in exact float32 with κ(A)\kappa(\mat{A}) from 1 to 107.510^{7.5} using three algorithms:

InteractiveStability map
Each point is a 6×66\times 6 system solved in your browser in float32 (each operation rounded with Math.fround, reproducing float32 arithmetic), compared with the double-precision solution of the same data. One panel shows forward error, the other Rigal-Gaches backward error; dashed lines are u=2−24u = 2^{-24}, κu\kappa u and κ2u\kappa^2 u, and errors above 10 appear at the upper edge. Notice each algorithm's backward-error cloud: flat at uu for elimination, increasing for inverse, increasing and truncated (Cholesky fails) for normal equations. Then compare elimination and inverse forward-error clouds: are they as distinct?
  • Pivoted elimination (what np.linalg.solve does) is backward stable: η\eta stays at uu for any κ\kappa, and forward error follows κu\kappa u.
  • Multiplication by the computed inverse, x^=fl⁡(X^b)\hat{\vb{x}} = \operatorname{fl}(\hat{\mat{X}}\vb{b}) with X^≈A−1\hat{\mat{X}} \approx \mat{A}\inv, has similar forward error (order κu\kappa u, slightly larger than elimination), but backward error grows almost proportionally to κ\kappa (on the map from uu to nearly 106u10^6 u): it is not backward stable. Its residual can be order κu∥A∥∥x^∥\kappa u\norm{\mat{A}}\norm{\hat{\vb{x}}} rather than u∥A∥∥x^∥u\norm{\mat{A}}\norm{\hat{\vb{x}}}. It also costs about three times as many operations. This motivates “never compute an inverse to solve a system.”
  • Normal equations A⊤Ax=A⊤b\mat{A}\T\mat{A}\vb{x} = \mat{A}\T\vb{b} solve a different problem with condition number κ(A⊤A)=κ(A)2\kappa(\mat{A}\T\mat{A}) = \kappa(\mat{A})^2: forward error follows κ2u\kappa^2 u, so when κ2u\kappa^2 u approaches 1 (in float32, κ≈4×103\kappa \approx 4\times 10^3), barely one digit remains, and soon none; at larger κ\kappa, computed A⊤A\mat{A}\T\mat{A} often ceases to be positive definite and Cholesky fails (first at κ≈5×104\kappa \approx 5\times 10^4 on the map). It is unstable for problem Ax=b\mat{A}\vb{x} = \vb{b} because it passes through a worse-conditioned intermediate problem, just like Wilkinson’s polynomial.

Unstable recurrences

The cleanest unstable-algorithm case has no matrices. Consider

In=∫01xnex−1 ⁣dx,n=0,1,2,…I_n = \int_0^1 x^n e^{x - 1}\dd x, \qquad n = 0, 1, 2, \dots

Since e−1≤ex−1≤1e^{-1} \le e^{x - 1} \le 1 on [0,1][0, 1], 1e(n+1)<In<1n+1\frac{1}{e(n + 1)} < I_n < \frac{1}{n + 1} holds: InI_n are positive and tend to zero. Integrating by parts with u=xnu = x^n and  ⁣dv=ex−1 ⁣dx\dd v = e^{x - 1}\dd x,

In=[xnex−1]01−n∫01xn−1ex−1 ⁣dx=1−n In−1,I0=1−e−1.I_n = \Big[x^n e^{x - 1}\Big]_0^1 - n\int_0^1 x^{n - 1}e^{x - 1}\dd x = 1 - n\,I_{n - 1}, \qquad I_0 = 1 - e^{-1}.

An exact one-line recurrence. Compute it in float64.

[ ]Forward and backward recurrenceBrowser
import math
import mpmath as mp

# referencia: la misma recurrencia con 60 cifras (pierde unas 25 por el camino y le sobran)
mp.mp.dps = 60
exacto = [1 - 1 / mp.e]
for n in range(1, 26):
    exacto.append(1 - n * exacto[-1])

# hacia delante en float64
I = [1 - 1 / math.e]
for n in range(1, 26):
    I.append(1 - n * I[-1])
e0 = float(I[0] - exacto[0])
print(f"I_0 = {I[0]!r},  error inicial e_0 = {e0:.4e}\n")
print(" n   hacia delante        exacto          error        n! * e_0 * (-1)^n")
for n in [0, 5, 10, 14, 15, 16, 17, 18, 19, 20, 25]:
    err = float(I[n] - exacto[n])
    print(f"{n:2d}  {I[n]:16.8e}  {float(exacto[n]):14.8e}  {err:11.3e}   {(-1)**n * math.factorial(n) * e0:11.3e}")

# hacia atrás desde I_N = 0
for N in (20, 25, 30):
    J, atras = 0.0, {}
    for n in range(N, 0, -1):
        J = (1 - J) / n                          # J pasa a valer I_{n-1}
        atras[n - 1] = J
    print(f"\nhacia atrás desde N = {N}: " + ",  ".join(
        f"error en I_{m} = {abs(atras[m] - float(exacto[m])):.1e}" for m in (15, 10, 0)))

print(f"\ncondición de I_0 -> I_20:  20! * I_0 / I_20 = {math.factorial(20) * float(exacto[0] / exacto[20]):.2e}")

Through n=13n = 13 all seems well; at n=17n = 17 the result is already 8% higher, at n=18n = 18 it is negative (the integral of a positive function), and at n=25n = 25 it is 1.9×1081.9\times 10^{8}. The last column explains the disaster. If I^n−1=In−1+en−1\hat I_{n - 1} = I_{n - 1} + e_{n - 1}, then I^n=1−nI^n−1=In−n en−1\hat I_n = 1 - n\hat I_{n - 1} = I_n - n\,e_{n - 1}: error is multiplied by −n-n at each step, and

en=(−1)n n! e0.e_n = (-1)^n\,n!\,e_0.

Initial error is only rounding of 1−1/e1 - 1/e, e0≈−1.24×10−17e_0 \approx -1.24\times 10^{-17}, and the error column matches (−1)nn! e0(-1)^n n!\,e_0 to all printed digits: subsequent roundings are negligible beside that snowball. For n=20n = 20, 20!≈2.4×101820! \approx 2.4\times 10^{18} turns 10−1710^{-17} into 30.

Reversed, the same mechanism helps. With In−1=(1−In)/nI_{n - 1} = (1 - I_n)/n, error in InI_n is divided by nn at each step: em=(−1)N−m m!N! eNe_m = (-1)^{N - m}\,\frac{m!}{N!}\,e_N. Start at N=30N = 30 with absurd value I30=0I_{30} = 0 (error 0.030.03, 100%) and by n=15n = 15 that error is divided by 30!/15!≈2×102030!/15! \approx 2\times 10^{20}: the cell shows zero error, the exact value rounded to float64. From N=20N = 20, however, error at I15I_{15} is still 2.4×10−82.4\times 10^{-8}: choose the starting point with margin.

InteractiveAn exploding recurrence
Above are computed InI_n values (red forward, teal backward, dashed gray reference); below is absolute error on a log scale with prediction n! ∣e0∣n!\,\abs{e_0} dashed. Everything is calculated in float64 in your browser with the preceding cell's operations, so numbers agree. Play the animation and watch red error: on a log scale it rises like log⁡10n!\log_{10} n!, increasingly steep because each step multiplies by a larger nn. Add a 10−1010^{-10} perturbation to I0I_0 and see how much sooner everything is lost. Move NN toward 25 or start at 1/(N+1)1/(N + 1) and see which part of the teal curve changes.

Which is responsible, problem or algorithm? The problem “calculate I20I_{20}” has no erroneous data: its condition number is irrelevant, and backward recurrence obtains I20I_{20} to all digits. The forward algorithm is responsible: it turns computation into intermediate problem “obtain I20I_{20} from I0I_0.” That intermediate problem is affine, I20=c−20! I0I_{20} = c - 20!\,I_0 for a constant cc, with condition number 20! I0/I20≈3.4×101920!\,I_0/I_{20} \approx 3.4\times 10^{19}. An algorithm is unstable when it passes through a worse-conditioned subproblem than the one it solves: forward recurrence, Wilkinson’s characteristic polynomial and normal equations do this.

Implementation: experimental conditioning

Formulas for κ\kappa need derivatives, not always available. The definition suggests an experimental method: randomly perturb data with small relative size δ\delta, measure relative-error amplification and keep the maximum. First use the magnifier’s scalar functions.

[ ]Experimental κ of scalar functionsBrowser
import numpy as np

rng = np.random.default_rng(0)

def kappa_experimental(f, x, delta=1e-7, pruebas=200):
    """Máximo de (|f(x') - f(x)|/|f(x)|) / (|x' - x|/|x|) con x' = x(1 + delta*s), s uniforme en [-1, 1]."""
    fx = f(x)
    s = rng.uniform(-1, 1, pruebas)
    xp = x * (1 + delta * s)
    amp = np.abs(f(xp) - fx) / abs(fx) / (np.abs(xp - x) / abs(x))
    return amp.max()

casos = [
    ("log x,   x = 1.0001", np.log, 1.0001, 1 / abs(np.log(1.0001))),
    ("tan x,   x = 1.57", np.tan, 1.57, abs(2 * 1.57 / np.sin(2 * 1.57))),
    ("sqrt x,  x = 2", np.sqrt, 2.0, 0.5),
    ("x - 1,   x = 1.001", lambda v: v - 1, 1.001, 1.001 / 0.001),
    ("raíz de x^2 - 2x + c,  c = 0.9999", lambda c: 1 + np.sqrt(1 - c), 0.9999,
     0.9999 / (2 * np.sqrt(1 - 0.9999) * (1 + np.sqrt(1 - 0.9999)))),
]
for nombre, f, x, k in casos:
    print(f"{nombre:36s} experimental {kappa_experimental(f, x):12.7g}   fórmula {k:12.7g}")

The columns agree to three or four digits. Agreement is imperfect for two reasons: with δ=10−7\delta = 10^{-7} a second-order term remains (relative, of order κδ\kappa\delta), and rounding when calculating f(x′)f(x') and f(x)f(x) in float64 adds relative error of order u/(κδ)u/(\kappa\delta) to each ratio. The table shows the first: for tangent, relative difference between columns is 2×10−4≈κδ2\times 10^{-4} \approx \kappa\delta. Choosing δ\delta is the same truncation-rounding tradeoff as finite differences.

With a matrix the perturbation has a direction, making the definition’s supremum important. For x=A−1b\vb{x} = \mat{A}\inv\vb{b} as a function of b\vb{b}, amplification ∥δx∥/∥x∥∥δb∥/∥b∥\frac{\norm{\delta\vb{x}}/\norm{\vb{x}}}{\norm{\delta\vb{b}}/\norm{\vb{b}}} reaches κ2(A)\kappa_2(\mat{A}) only if b\vb{b} points in the direction stretched most by A\mat{A}, u1\vb{u}_1, and δb\delta\vb{b} in the least-stretched direction, un\vb{u}_n (the extreme columns of the SVD).

[ ]Experimental matrix κ: the worst case is rareBrowser
import numpy as np

rng = np.random.default_rng(1)
n = 50
U, _ = np.linalg.qr(rng.standard_normal((n, n)))
V, _ = np.linalg.qr(rng.standard_normal((n, n)))
s = np.logspace(0, -6, n)                         # valores singulares de 1 a 1e-6
A = U @ np.diag(s) @ V.T
kappa = s[0] / s[-1]

def ampliacion(b, db):
    x = np.linalg.solve(A, b)
    dx = np.linalg.solve(A, b + db) - x
    return (np.linalg.norm(dx) / np.linalg.norm(x)) / (np.linalg.norm(db) / np.linalg.norm(b))

def kappa_b(b):                                   # condición de b -> A^{-1} b con A fija
    return np.linalg.norm(b) / (s[-1] * np.linalg.norm(np.linalg.solve(A, b)))

b_aleatorio = rng.standard_normal(n)
amps = [ampliacion(b_aleatorio, 1e-8 * rng.standard_normal(n)) for _ in range(200)]
print(f"kappa_2(A) = {kappa:.3e}")
print(f"condición de b -> x en b aleatorio: {kappa_b(b_aleatorio):.3e};   en b = u_1: {kappa_b(U[:, 0]):.3e}\n")
print(f"b y db aleatorios, máximo en 200 pruebas:   {max(amps):.3e}")
print(f"b = u_1 y db aleatorios, máximo:            {max(ampliacion(U[:, 0], 1e-8 * rng.standard_normal(n)) for _ in range(200)):.3e}")
print(f"b = u_1 y db = 1e-8 u_n (el peor caso):     {ampliacion(U[:, 0], 1e-8 * U[:, -1]):.3e}")

With random b\vb{b} and δb\delta\vb{b}, maximum measured amplification is 3, six orders below κ=106\kappa = 10^6! The data explain this. With fixed A\mat{A}, condition number of problem b↦A−1b\vb{b} \mapsto \mat{A}\inv\vb{b} is ∥A−1∥∥b∥/∥x∥\norm{\mat{A}\inv}\norm{\vb{b}}/\norm{\vb{x}}, at most κ(A)\kappa(\mat{A}) but dependent on b\vb{b}. A random b\vb{b} has component of size ≈1/50\approx 1/\sqrt{50} along un\vb{u}_n, multiplied by A−1\mat{A}\inv by 10610^6: solution x\vb{x} is already huge, and another perturbation barely changes its relative size. The cell confirms this: conditioning at that b\vb{b} is 7.17.1 (and measured amplification 3 is lower still because random δb\delta\vb{b} do not point in the worst direction). With b=u1\vb{b} = \vb{u}_1, by contrast, the solution is as small as possible, conditioning equals 10610^6, and random δb\delta\vb{b} suffices for amplification 3.7×1053.7\times 10^5 times (its component on un\vb{u}_n again has ≈1/50\approx 1/\sqrt{50} of its norm); with δb=un\delta\vb{b} = \vb{u}_n, κ\kappa is attained exactly. Two lessons: κ(A)\kappa(\mat{A}) is a worst-case bound that can be very pessimistic for a specific input; estimating κ(A)\kappa(\mat{A}) using random perturbations underestimates it. Good estimators (such as LAPACK’s, below) actively seek the bad direction.

Hilbert matrices

Hilbert matrix Hn\mat{H}_n, with hij=1/(i+j−1)h_{ij} = 1/(i + j - 1), is the classic ill-conditioning testbed. To cleanly separate problem and algorithm, the cell calculates the exact solution of the system actually stored in memory (with Hn\mat{H}_n and b\vb{b} already rounded to float64), using rational arithmetic, and exact condition number κ∞\kappa_\infty using the integer inverse given by scipy.linalg.invhilbert.

[ ]Hilbert: residual, error and lost digitsBrowser
import numpy as np
from fractions import Fraction
from scipy.linalg import hilbert, invhilbert
import matplotlib.pyplot as plt

def resolver_exacto(A, b):
    """Eliminación gaussiana en racionales: la solución exacta de los datos en coma flotante."""
    n = len(b)
    M = [[Fraction(v) for v in fila] + [Fraction(bi)] for fila, bi in zip(A.tolist(), b.tolist())]
    for k in range(n):
        p = next(i for i in range(k, n) if M[i][k] != 0)
        M[k], M[p] = M[p], M[k]
        for i in range(k + 1, n):
            l = M[i][k] / M[k][k]
            for j in range(k, n + 1):
                M[i][j] -= l * M[k][j]
    x = [Fraction(0)] * n
    for i in reversed(range(n)):
        x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
    return np.array([float(v) for v in x])

u = 2.0**-53
ns, logk, err, eta = [], [], [], []
print(" n   kappa_inf(H)   residuo relativo   error relativo   cifras   16 - log10(kappa)")
for n in range(2, 15):
    H = hilbert(n)
    b = H @ np.ones(n)
    x = resolver_exacto(H, b)
    xh = np.linalg.solve(H, b)
    k = np.abs(H).sum(axis=1).max() * np.abs(invhilbert(n, exact=True)).sum(axis=1).max()
    r = b - H @ xh
    e = np.linalg.norm(xh - x, np.inf) / np.linalg.norm(x, np.inf)
    et = np.linalg.norm(r, np.inf) / (np.linalg.norm(H, np.inf) * np.linalg.norm(xh, np.inf) + np.linalg.norm(b, np.inf))
    ns.append(n); logk.append(np.log10(float(k))); err.append(e); eta.append(et)
    print(f"{n:2d}   {float(k):11.3e}   {et:15.2e}   {e:14.2e}   {-np.log10(e):6.1f}   {16 - np.log10(float(k)):8.1f}")

plt.semilogy(ns, err, "o-", label="error relativo hacia delante")
plt.semilogy(ns, eta, "s-", label="error hacia atrás (Rigal-Gaches)")
plt.semilogy(ns, [10.0**l * u for l in logk], "--", color="gray", label="κ·u")
plt.axhline(u, color="gray", lw=0.8, ls=":", label="u")
plt.xlabel("n"); plt.ylabel("norma ∞"); plt.legend(); plt.show()

The table shows the lost-digit rule in action. Backward error never exceeds 8×10−178\times 10^{-17}, below uu, for any nn (exactly 0 for n=2n = 2 and 33): np.linalg.solve does its job perfectly for any nn. Forward error grows with κ\kappa, always below κu\kappa u, and obtained digits are one or two above prediction 16−log⁡10κ16 - \log_{10}\kappa because the bound is worst-case. With n=12n = 12 less than one correct digit remains, and with n=13n = 13 and 1414, with κ∞>1018\kappa_\infty > 10^{18}, relative error exceeds 100% with the same tiny residual.

Backward error of system solutions

Second lab. Function eta_rg implements the Rigal-Gaches theorem in 2-norm and constructs optimal perturbations ΔA\Delta\mat{A} and Δb\Delta\vb{b} from the proof to check that they make the solution exact.

[ ]Rigal-Gaches: a small residual is not a good solutionBrowser
import numpy as np
from scipy.linalg import hilbert

def eta_rg(A, b, x):
    """Error hacia atrás normwise en norma 2 y las perturbaciones que lo alcanzan."""
    r = b - A @ x
    nA, nx, nb = np.linalg.norm(A, 2), np.linalg.norm(x), np.linalg.norm(b)
    D = nA * nx + nb
    dA = (nA / D) * np.outer(r, x / nx)
    db = -(nb / D) * r
    return np.linalg.norm(r) / D, dA, db

n = 10
H = hilbert(n)
x_ex = np.ones(n)
b = H @ x_ex
_, sv, Vt = np.linalg.svd(H)
print(f"kappa_2(H_10) = {sv[0] / sv[-1]:.2e}\n")

candidatas = {
    "np.linalg.solve (LAPACK)": np.linalg.solve(H, b),
    "solución + 0.1 v_n": x_ex + 0.1 * Vt[-1],     # v_n: dirección que H casi anula
    "solución + 1e-6 v_1": x_ex + 1e-6 * Vt[0],    # v_1: dirección que H más estira
}
print(f"{'candidata':26s} {'eta':>10s} {'error hacia delante':>20s} {'2 kappa eta':>12s}")
for nombre, xh in candidatas.items():
    eta, dA, db = eta_rg(H, b, xh)
    fwd = np.linalg.norm(xh - x_ex) / np.linalg.norm(x_ex)
    print(f"{nombre:26s} {eta:10.2e} {fwd:20.2e} {2 * sv[0] / sv[-1] * eta:12.2e}")

eta, dA, db = eta_rg(H, b, candidatas["solución + 0.1 v_n"])
print("\ncomprobación con la candidata estropeada en v_n:")
print(f"  ||(H + dA) x - (b + db)|| = {np.linalg.norm((H + dA) @ candidatas['solución + 0.1 v_n'] - (b + db)):.1e}")
print(f"  ||dA|| / ||H|| = {np.linalg.norm(dA, 2) / sv[0]:.3e}   ||db|| / ||b|| = {np.linalg.norm(db) / np.linalg.norm(b):.3e}")

Here x=(1,…,1)\vb{x} = (1, \dots, 1) is the reference solution (rounding b\vb{b} moves it at κu≈10−3\kappa u \approx 10^{-3} level, changing no conclusion). Three candidates tell the whole story:

  • LAPACK’s has η=5.3×10−17\eta = 5.3\times 10^{-17}: it is the exact solution of a system less than uu away from yours. Its forward error, 1.7×10−41.7\times 10^{-4}, comes from the problem.
  • The candidate corrupted along vn\vb{v}_n has forward error 3%, two hundred times larger than LAPACK’s, yet backward error 1.1×10−151.1\times 10^{-15}, about ten units of roundoff: H\mat{H} nearly annihilates that direction, so the residual barely sees it. Looking only at residual, this candidate seems almost as good as LAPACK’s.
  • The candidate corrupted along v1\vb{v}_1 has tiny forward error 3×10−73\times 10^{-7} and enormous residual relative to uu. The large residual reveals poor computation even though the solution is more accurate than LAPACK’s.

The final check completes the theorem: constructed perturbations make the candidate exact up to rounding, with relative sizes equal to η\eta.

Now compare the stability map in float64, with an exact rational reference.

[ ]solve versus inv: residual distinguishes what error does notBrowser
import numpy as np
from fractions import Fraction

rng = np.random.default_rng(1)
n = 8

def ortogonal(n):
    Q, R = np.linalg.qr(rng.standard_normal((n, n)))
    return Q * np.sign(np.diag(R))

def exacta(A, b):
    return resolver_exacto(A, b)               # definida en la celda de Hilbert

def eta2(A, b, x):
    return np.linalg.norm(b - A @ x) / (np.linalg.norm(A, 2) * np.linalg.norm(x) + np.linalg.norm(b))

print(" log10 kappa |  solve: delante    atrás  |  inv: delante    atrás")
for lk in [0, 2, 4, 6, 8, 10, 12, 14]:
    A = ortogonal(n) @ np.diag(np.logspace(0, -lk, n)) @ ortogonal(n).T
    b = A @ rng.standard_normal(n)
    x = exacta(A, b)
    fila = []
    for xh in (np.linalg.solve(A, b), np.linalg.inv(A) @ b):
        fila.append(f"{np.linalg.norm(xh - x) / np.linalg.norm(x):9.1e} {eta2(A, b, xh):9.1e}")
    print(f"     {np.log10(np.linalg.cond(A)):5.1f}   | {fila[0]}  | {fila[1]}")

Forward-error columns for solve and inv both grow like κu\kappa u; inv is slightly worse (at κ=1014\kappa = 10^{14} it reaches 4×10−24\times 10^{-2}, versus 2×10−42\times 10^{-4} for solve and κu≈10−2\kappa u \approx 10^{-2}). Backward-error columns differ completely: solve stays below uu for any κ\kappa, whereas inv grows with it and reaches 1.5×10−41.5\times 10^{-4} when κ=1014\kappa = 10^{14}. Looking only at forward error (unknown in real life), the algorithms seem equally good. Calculable backward error separates them.

Returning to regression

Now diagnose the motivation. The “least-squares coefficients” problem has a condition number depending on κ2(X)\kappa_2(\mat{X}) (and, if residual is not small, κ2(X)2\kappa_2(\mat{X})^2 with an attenuating factor; full analysis appears in numerical least squares). Normal equations always solve a system with κ(X⊤X)=κ(X)2\kappa(\mat{X}\T\mat{X}) = \kappa(\mat{X})^2 instead. The cell computes the exact answer for stored data using rational arithmetic.

[ ]Regression diagnosisBrowser
import numpy as np
from fractions import Fraction

# solución exacta de las ecuaciones normales de los datos en float64 (equivalen al problema de mínimos cuadrados)
XF = [[Fraction(v) for v in fila] for fila in X.tolist()]
yF = [Fraction(v) for v in y.tolist()]
G = np.array([[float(sum(XF[k][i] * XF[k][j] for k in range(60))) for j in range(13)] for i in range(13)])
G_exacta = [[sum(XF[k][i] * XF[k][j] for k in range(60)) for j in range(13)] for i in range(13)]
h_exacta = [sum(XF[k][i] * yF[k] for k in range(60)) for i in range(13)]

def resolver_fracciones(M, v):
    n = len(v)
    M = [fila[:] + [vi] for fila, vi in zip(M, v)]
    for k in range(n):
        for i in range(k + 1, n):
            l = M[i][k] / M[k][k]
            for j in range(k, n + 1):
                M[i][j] -= l * M[k][j]
    x = [Fraction(0)] * n
    for i in reversed(range(n)):
        x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
    return np.array([float(t) for t in x])

c_ex = resolver_fracciones(G_exacta, h_exacta)
k = np.linalg.cond(X)
print(f"kappa_2(X) = {k:.2e},   kappa_2(X^T X) = kappa^2 = {k**2:.2e},   kappa * u = {k * 2.0**-53:.1e}")
for nombre, c in (("ecuaciones normales", c_ne), ("lstsq", c_ls)):
    ec = np.linalg.norm(c - c_ex) / np.linalg.norm(c_ex)
    ep = np.linalg.norm(X @ c - X @ c_ex) / np.linalg.norm(X @ c_ex)
    print(f"{nombre:20s} error en los coeficientes {ec:9.2e}   error en las predicciones {ep:9.2e}")

The complete diagnosis:

  • The coefficient problem is ill conditioned: κ2(X)≈6.8×108\kappa_2(\mat{X}) \approx 6.8\times 10^8, because Vandermonde columns t10,t11,t12t^{10}, t^{11}, t^{12} are nearly parallel in [0,1][0, 1]. Even backward-stable lstsq can guarantee only about 16−8.8≈716 - 8.8 \approx 7 digits and obtains error 6.8×10−86.8\times 10^{-8}: 7 digits. This is the best possible and comes from the problem. Regression multicollinearity is exactly this: ill-conditioning of the design matrix.
  • Normal equations are unstable for this problem: κ2u≈50\kappa^2 u \approx 50, so the system they solve retains no coefficient digits (119% error). The algorithm is responsible and can be replaced.
  • Predictions Xc\mat{X}\vb{c} are a much better-conditioned problem than coefficients: very different c\vb{c} directions give nearly the same curve, exactly what ill-conditioned X\mat{X} means. Thus the two curves nearly agreed: lstsq predictions have error 3×10−113\times 10^{-11}, and normal-equation predictions 4×10−44\times 10^{-4}, while their coefficients have no correct digits. For prediction regression is reliable with lstsq; for coefficient interpretation no algorithm makes it reliable, so change the problem: another basis (Chebyshev or orthogonal polynomials), lower degree or regularization.

In libraries

Estimating κ(A)\kappa(\mat{A}) is routine work, with three methods of very different cost.

ToolWhat it calculatesCost
np.linalg.cond(A)κ2=σ1/σn\kappa_2 = \sigma_1/\sigma_n with SVDO(n3)\bigO(n^3), several times the cost of solving the system
np.linalg.cond(A, 1) or np.inf∥A∥∥A−1∥\norm{\mat{A}}\norm{\mat{A}\inv} by forming inv(A)O(n3)\bigO(n^3) and an unnecessary inverse
scipy.linalg.lapack.dgeconestimate of 1/κ11/\kappa_1 from existing LUO(n2)\bigO(n^2): nearly free if already factored
scipy.linalg.solvesolves and estimates rcond with geconwarns with LinAlgWarning if rcond falls to machine-epsilon level

LAPACK’s estimator (routines xGECON, calling xLACN2) implements Hager’s method with Higham’s 1988 improvements: it estimates ∥A−1∥1\norm{\mat{A}\inv}_1 by solving a few systems with LU factors, actively seeking the most amplified vector. It is not exact, but almost always gets the order of magnitude, what matters for counting digits.

[ ]Estimate κ without forming the inverseBrowser
import warnings
import numpy as np
import scipy.linalg as sl
from scipy.linalg import hilbert, invhilbert
from scipy.linalg.lapack import dgetrf, dgecon

for n in (6, 10, 13):
    H = hilbert(n)
    k1_exacto = np.abs(H).sum(axis=0).max() * float(np.abs(invhilbert(n, exact=True)).sum(axis=0).max())
    lu, piv, info = dgetrf(H)
    rcond, info = dgecon(lu, np.abs(H).sum(axis=0).max(), norm="1")
    print(f"n = {n:2d}:  kappa_1 exacto = {k1_exacto:.3e}   1/rcond de dgecon = {1 / rcond:.3e}   "
          f"np.linalg.cond(H) = {np.linalg.cond(H):.3e}")

with warnings.catch_warnings(record=True) as avisos:
    warnings.simplefilter("always")
    sl.solve(hilbert(13), np.ones(13))
    np.linalg.solve(hilbert(13), np.ones(13))
print("\navisos emitidos:", [f"{a.category.__name__}: {a.message}" for a in avisos])

The estimator gets κ1\kappa_1 right to all four printed digits for n=6n = 6 and 1010 (the last column is κ2\kappa_2, another norm, hence differs by factor 2). For n=13n = 13, with κ>1/u\kappa > 1/u, no float64 method can give the exact value (including np.linalg.cond, whose SVD calculates σn\sigma_n with absolute error of order uσ1u\sigma_1, larger than σn\sigma_n itself), but both correctly say κ\kappa is of order 1/u1/u or larger, all you need to know. Notice which function warns: scipy.linalg.solve emits LinAlgWarning; np.linalg.solve silently returns a result.

Common mistakes

Exercises

NumericLogarithm near 1
Calculate the relative condition number of f(x)=log⁡xf(x) = \log x at x=1.0001x = 1.0001.
NumericTangent near the pole
Calculate the relative condition number of tan⁡x\tan x at x=1.57x = 1.57.
NumericThe snowball
In recurrence I^n=1−n I^n−1\hat I_n = 1 - n\,\hat I_{n-1}, suppose I^0\hat I_0 has absolute error 10−1610^{-16} and all other operations are exact. What absolute error does I^20\hat I_{20} have?
NumericA tiny residual, a wrong solution
Let A=[1111.0001]\mat{A} = \begin{bmatrix} 1 & 1 \\ 1 & 1.0001 \end{bmatrix}, b=(2, 2.0001)\vb{b} = (2,\ 2.0001), with exact solution (1,1)(1, 1), and candidate x^=(2,0)\hat{\vb{x}} = (2, 0). Calculate its Rigal-Gaches backward error in ∞\infty-norm, η=∥r∥∞/(∥A∥∞∥x^∥∞+∥b∥∞)\eta = \norm{\vb{r}}_\infty/(\norm{\mat{A}}_\infty\norm{\hat{\vb{x}}}_\infty + \norm{\vb{b}}_\infty).
QuizHow many digits?
You solve Ax=b\mat{A}\vb{x} = \vb{b} in float64 and get relative residual ∥b−Ax^∥/(∥A∥∥x^∥)≈10−16\norm{\vb{b} - \mat{A}\hat{\vb{x}}}/(\norm{\mat{A}}\norm{\hat{\vb{x}}}) \approx 10^{-16}. An estimator reports κ(A)≈1012\kappa(\mat{A}) \approx 10^{12}. How many correct digits should you expect in x^\hat{\vb{x}} in the worst case?
QuizSubtraction in two questions
Let x1x_1 and x2x_2 be positive, very close machine numbers. What is true of operation fl⁡(x1−x2)\operatorname{fl}(x_1 - x_2) and problem f(x1,x2)=x1−x2f(x_1, x_2) = x_1 - x_2?
QuizClassify the algorithms
Which floating-point algorithms are backward stable for the stated problem?

More than one answer may be correct.

QuizProblem or algorithm?
In which cases is a poor result caused by the algorithm, so another algorithm at the same precision would fix it?

More than one answer may be correct.

QuizA tiny determinant
A matrix A∈R50×50\mat{A} \in \R^{50\times 50} has det⁡A=10−50\det\mat{A} = 10^{-50}. What can you conclude about solving Ax=b\mat{A}\vb{x} = \vb{b}?
ProofForward ≲ κ · backward
Prove: Let ff be C2C^2 in a ball B(x,ρ)B(\vb{x}, \rho), with x≠0\vb{x} \neq \vb{0} and f(x)≠0f(\vb{x}) \neq \vb{0}. If y^=f(x+Δx)\hat{\vb{y}} = f(\vb{x} + \Delta\vb{x}) with ∥Δx∥≤η∥x∥\norm{\Delta\vb{x}} \le \eta\norm{\vb{x}} and η∥x∥<ρ\eta\norm{\vb{x}} < \rho, then ∥y^−f(x)∥/∥f(x)∥≤κ(x) η+O(η2)\norm{\hat{\vb{y}} - f(\vb{x})}/\norm{f(\vb{x})} \le \kappa(\vb{x})\,\eta + \bigO(\eta^2).
0
Let J=J(x)\mat{J} = \mat{J}(\vb{x}) be the Jacobian and MM bound the norm of the second derivative of ff on the ball.

Step 1 of 4. What do you first write for y^−f(x)\hat{\vb{y}} - f(\vb{x})?

CodeBackward error and its certificate
Implement backward_error(A, b, x_hat, ord=2) returning (eta, dA, db): the Rigal-Gaches normwise backward error η=∥r∥/(∥A∥∥x^∥+∥b∥)\eta = \norm{\vb{r}}/(\norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}}) with r=b−Ax^\vb{r} = \vb{b} - \mat{A}\hat{\vb{x}}, and perturbations dA, db attaining it: (A+ΔA)x^=b+Δb(\mat{A} + \Delta\mat{A})\hat{\vb{x}} = \vb{b} + \Delta\vb{b} with ∥ΔA∥=η∥A∥\norm{\Delta\mat{A}} = \eta\norm{\mat{A}} and ∥Δb∥=η∥b∥\norm{\Delta\vb{b}} = \eta\norm{\vb{b}}. ord can be 2 (2-norm and spectral norm) or np.inf (∞\infty-norm and its operator norm, maximum row sum). If x_hat is the zero vector, the only input making it exact is b+Δb=0\vb{b} + \Delta\vb{b} = \vb{0}: return η=1\eta = 1, zero dA and db = -b.
import numpy as np

def backward_error(A, b, x_hat, ord=2):
  """Devuelve (eta, dA, db) con (A + dA) x_hat = b + db, ||dA|| = eta ||A||, ||db|| = eta ||b||."""
  A = np.asarray(A, dtype=float)
  b = np.asarray(b, dtype=float)
  x = np.asarray(x_hat, dtype=float)
  r = b - A @ x
  # tu código: normas según ord, vector dual z de x (z @ x = ||x||, norma dual 1)
  # y las perturbaciones de la demostración
  return 0.0, np.zeros_like(A), np.zeros_like(b)
Shift+Enter to run

Summary

Key idea
A poor result has two possible causes: the problem, amplifying data errors by condition number κ\kappa, and the algorithm, which may add errors unjustified by the problem. A backward-stable algorithm gives the exact answer for data perturbed at uu level, with forward error at most order κu\kappa u: about log⁡10κ\log_{10}\kappa digits are lost and no algorithm can avoid it.
  • Relative condition number of problem ff is κ=∥J∥∥x∥/∥f(x)∥\kappa = \norm{\mat{J}}\norm{\vb{x}}/\norm{f(\vb{x})}, or ∣xf′(x)/f(x)∣\abs{x f'(x)/f(x)} in the scalar case. It explodes when subtracting nearby numbers, for log⁡x\log x near 1, tan⁡x\tan x near poles and zeros, and multiple or clustered polynomial roots; Wilkinson showed roots 1,…,201, \dots, 20 suffice to reach κ≈1013\kappa \approx 10^{13}.
  • Forward error compares result to exact value; backward error seeks nearest data for which the result is exact. Backward stable: exact answer to a nearly identical question. Stable: nearly exact answer to a nearly identical question. Subtraction, dot product, square root and pivoted elimination are backward stable; outer product and x+1x + 1 are only stable; Cramer’s rule in 2×22\times 2 and inverse multiplication give forward errors of order κu\kappa u but are not backward stable.
  • Forward error ≲κ⋅\lesssim \kappa \cdot backward error +O(η2)+ \bigO(\eta^2). For linear systems backward error has closed form η=∥r∥/(∥A∥∥x^∥+∥b∥)\eta = \norm{\vb{r}}/(\norm{\mat{A}}\norm{\hat{\vb{x}}} + \norm{\vb{b}}) (Rigal and Gaches), and forward error is at most 2κ(A)η/(1−κη)2\kappa(\mat{A})\eta/(1 - \kappa\eta). A small residual certifies stability, not accuracy.
  • Unstable algorithms often pass through a worse-conditioned subproblem: forward recurrence In=1−nIn−1I_n = 1 - nI_{n-1} (error × n!\times\,n!), characteristic-polynomial coefficients, normal equations (κ2\kappa^2).
  • κ\kappa is estimated without forming the inverse: gecon in O(n2)\bigO(n^2) after LU, or SVD if accurate κ2\kappa_2 is needed. scipy.linalg.solve warns; np.linalg.solve does not. Determinant measures none of this.