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 minimizing , with the points’ Vandermonde matrix. A colleague solves it with normal equations, , and you with np.linalg.lstsq. Both programs are correct in exact arithmetic and finish without warnings.
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 in one case and in the other, the fourth and , 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:
- 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.
- 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 between normed spaces (in practice open subsets of and ) mapping data to solution . Subtracting two numbers is problem ; solving a system is ; polynomial roots are a function of coefficients. Conditioning asks a purely mathematical question: if moves slightly, how much does move?
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 is differentiable at with Jacobian , then , and the supremum of ratio is by definition the operator norm of :
In the scalar case, with differentiable at , the most frequently used formula is:
The second form says what measures: the elasticity of , the percentage output change per one-percent data change. It also has a useful decimal-digit interpretation: relative data error (data have correct digits) gives relative solution error up to , with correct digits. A problem with condition number consumes about digits, whatever the algorithm. Use vector norms appropriate to the problem; changing norm changes by at most a factor depending on dimension, not data.
Four examples worth remembering
Subtracting nearby numbers. For with data norm , the Jacobian is , with norm (as a mapping from to ), so
If each datum carries its own relative error, (as when rounding), componentwise calculation gives . In both versions, subtracting numbers agreeing in their first digits has . 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 . The interactive shows this with : , which explodes at .
Logarithm near 1. With , . Away from it is moderate, but at with small , and : datum has . Notice the subtlety: ill-conditioning depends on what is considered the data. If is known accurately (for example, a small financial return), the problem is , with . Computing np.log(1 + s) turns a well-conditioned problem into an ill-conditioned one by forming , discarding the last digits of ; np.log1p(s) directly solves the well-conditioned problem. This is one of the previous lesson’s stable reformulations.
Tangent near . . It explodes at poles (, where ) and at zeros with (): at , . Since is not a machine number, np.tan(np.pi / 2) returns rather than infinity: stored input is distance from the pole. Its tangent is computed accurately, but there , so representation error of relatively suffices to make the result unrelated to the intended value.
Polynomial roots. Let be a simple root of , i.e. and . Consider as a function of coefficient . Differentiating identity with respect to (justified by the implicit function theorem, because ),
At a double root, and : the interactive shows this with the larger root of , equal to and colliding with the other at . 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, , and obtained disastrous results. The preceding formula explains why. Roots are , all simple and separated by 1, with . The coefficient of is , so the condition number of root with respect to it is
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 , and the worst combination (root 14 relative to coefficient ) reaches . Thus rounding coefficients to float64, with relative error , can already move some roots in their third digit. Wilkinson made the definitive experiment: he changed from to , a relative change of .
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, , is almost 3 units from original roots 16 and 17. Linear prediction 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 is no longer small, it only says the problem is lost.
The slider reveals the critical order of magnitude: the first real roots collide and leave the axis at , long before . The first collisions are center-right (around 14 to 17), precisely those with largest . 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 , seen as eigenvalues of symmetric matrix , is perfectly stable: perturbing the matrix with moves each eigenvalue by at most , 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 , the computer evaluates function (the floating-point program) and obtains . There are two ways to measure its error.
Forward error is what you would like to know, but requires the exact answer. Backward error answers another question: for which data is the exact answer? If those data are distance from yours, and your data already carried measurement or rounding errors of that size, 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 , , where is float64’s unit roundoff:
- Square root. . Relative forward error: . Backward error: , so is the exact root of and . Both are small.
- Adding 1 to a tiny number. With , . Relative forward error is , tiny. But the only datum giving exactly 1 is , at relative distance : 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, means “bounded by with constant that may depend on problem dimension but not datum .”
Backward stable implies stable (take the same 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, , 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 , 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. : it is exact subtraction of two data relatively perturbed by . If data arrive rounded, , total perturbation is below . Yet the result may have no correct digits: subtraction is not at fault; the problem has .
- The dot product is backward stable. Summing left to right, with (if ): it is the exact dot product of and perturbed vector .
- Outer product is stable but not backward stable. Each entry has relative error , so it is stable. But the computed matrix with entries almost never has rank 1, and thus is not for any vector pair: no nearby input makes it exact.
- Floating-point is stable but not backward stable, by the earlier example: has relative error , unbounded as .
- 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.
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 · 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 condition number × backward error, separating responsibilities: the problem supplies factor , the algorithm factor . For an algorithm that is merely stable, the same argument gives , where is relative error added to output by the algorithm. In decimal digits, with a backward-stable float64 algorithm:
| expected correct digits | example | |
|---|---|---|
| to | 15 or 16 | , away from 1, orthogonal systems |
| about 12 | ||
| about 6 | Hilbert matrix | |
| or more | none | Hilbert matrix |
Diagnosis: the problem or the algorithm?
The theorem gives a procedure for the motivating case or any suspicious result:
- Estimate . If is comparable to observed error, the problem suffices to explain it.
- 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).
- Decide. If , the algorithm did its job and the problem is responsible: change the formulation, improve data or raise precision. If , the algorithm is unstable for that input: replace it.
Linear systems
The central problem is with invertible . Its conditioning is known from matrix norms and conditioning: perturbing relatively by moves by at most relative , where 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 and : there it is shown that if , relative error is at most , and each term is bounded by case .
∎To first order, : factor 2 appears because two data are perturbed and is practically irrelevant. To use the theorem we still need for a particular solution ; the answer is exact and surprisingly simple.
Rigal and Gaches backward error
Proof
Equation is equivalent to .
Lower bound. If and satisfy the equation with size , then , i.e. .
Attainment. Let and take a dual vector of : an with and (in the 2-norm, ; in the norm, with the largest-component index; in general one exists by Hahn-Banach). Define
Then . Since , the operator norm of is , so and : size exactly .
∎If only matrix perturbation is allowed (), the same argument gives , the relative residual, with in 2-norm. The two differ by at most factor 2, because and 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, , certifies as the exact solution of a system differing from yours at rounding level. It certifies stability, not accuracy.
- Forward error can reach . With and , the solution may have only 4 correct digits despite a “perfect” residual.
- A large residual is a reliable alarm: if , the algorithm did not behave backward stably on that input.
The interactive shows three things worth checking separately. With pivoted elimination, the backward-error curve remains flat below throughout the sweep and at all three precisions, while forward error rises with : backward stability in action. Thus the computed point falls inside the ellipse of points with ; that ellipse has semiaxes inversely proportional to singular values of , so its length is times its width: the problem, not the algorithm, determines how far can slide along the lines. With Cramer’s rule, forward error is the same order as elimination, but backward error grows with : in float16 with (), reaches versus with elimination. Cramer in 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 in exact float32 with from 1 to using three algorithms:
- Pivoted elimination (what
np.linalg.solvedoes) is backward stable: stays at for any , and forward error follows . - Multiplication by the computed inverse, with , has similar forward error (order , slightly larger than elimination), but backward error grows almost proportionally to (on the map from to nearly ): it is not backward stable. Its residual can be order rather than . It also costs about three times as many operations. This motivates “never compute an inverse to solve a system.”
- Normal equations solve a different problem with condition number : forward error follows , so when approaches 1 (in float32, ), barely one digit remains, and soon none; at larger , computed often ceases to be positive definite and Cholesky fails (first at on the map). It is unstable for problem 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
Since on , holds: are positive and tend to zero. Integrating by parts with and ,
An exact one-line recurrence. Compute it in float64.
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 all seems well; at the result is already 8% higher, at it is negative (the integral of a positive function), and at it is . The last column explains the disaster. If , then : error is multiplied by at each step, and
Initial error is only rounding of , , and the error column matches to all printed digits: subsequent roundings are negligible beside that snowball. For , turns into 30.
Reversed, the same mechanism helps. With , error in is divided by at each step: . Start at with absurd value (error , 100%) and by that error is divided by : the cell shows zero error, the exact value rounded to float64. From , however, error at is still : choose the starting point with margin.
Which is responsible, problem or algorithm? The problem “calculate ” has no erroneous data: its condition number is irrelevant, and backward recurrence obtains to all digits. The forward algorithm is responsible: it turns computation into intermediate problem “obtain from .” That intermediate problem is affine, for a constant , with condition number . 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 need derivatives, not always available. The definition suggests an experimental method: randomly perturb data with small relative size , measure relative-error amplification and keep the maximum. First use the magnifier’s scalar functions.
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 a second-order term remains (relative, of order ), and rounding when calculating and in float64 adds relative error of order to each ratio. The table shows the first: for tangent, relative difference between columns is . Choosing is the same truncation-rounding tradeoff as finite differences.
With a matrix the perturbation has a direction, making the definition’s supremum important. For as a function of , amplification reaches only if points in the direction stretched most by , , and in the least-stretched direction, (the extreme columns of the SVD).
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 and , maximum measured amplification is 3, six orders below ! The data explain this. With fixed , condition number of problem is , at most but dependent on . A random has component of size along , multiplied by by : solution is already huge, and another perturbation barely changes its relative size. The cell confirms this: conditioning at that is (and measured amplification 3 is lower still because random do not point in the worst direction). With , by contrast, the solution is as small as possible, conditioning equals , and random suffices for amplification times (its component on again has of its norm); with , is attained exactly. Two lessons: is a worst-case bound that can be very pessimistic for a specific input; estimating using random perturbations underestimates it. Good estimators (such as LAPACK’s, below) actively seek the bad direction.
Hilbert matrices
Hilbert matrix , with , 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 and already rounded to float64), using rational arithmetic, and exact condition number using the integer inverse given by scipy.linalg.invhilbert.
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 , below , for any (exactly 0 for and ): np.linalg.solve does its job perfectly for any . Forward error grows with , always below , and obtained digits are one or two above prediction because the bound is worst-case. With less than one correct digit remains, and with and , with , 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 and from the proof to check that they make the solution exact.
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 is the reference solution (rounding moves it at level, changing no conclusion). Three candidates tell the whole story:
- LAPACK’s has : it is the exact solution of a system less than away from yours. Its forward error, , comes from the problem.
- The candidate corrupted along has forward error 3%, two hundred times larger than LAPACK’s, yet backward error , about ten units of roundoff: 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 has tiny forward error and enormous residual relative to . 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 .
Now compare the stability map in float64, with an exact rational reference.
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 ; inv is slightly worse (at it reaches , versus for solve and ). Backward-error columns differ completely: solve stays below for any , whereas inv grows with it and reaches when . 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 (and, if residual is not small, with an attenuating factor; full analysis appears in numerical least squares). Normal equations always solve a system with instead. The cell computes the exact answer for stored data using rational arithmetic.
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: , because Vandermonde columns are nearly parallel in . Even backward-stable
lstsqcan guarantee only about digits and obtains error : 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: , so the system they solve retains no coefficient digits (119% error). The algorithm is responsible and can be replaced.
- Predictions are a much better-conditioned problem than coefficients: very different directions give nearly the same curve, exactly what ill-conditioned means. Thus the two curves nearly agreed:
lstsqpredictions have error , and normal-equation predictions , while their coefficients have no correct digits. For prediction regression is reliable withlstsq; 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 is routine work, with three methods of very different cost.
| Tool | What it calculates | Cost |
|---|---|---|
np.linalg.cond(A) | with SVD | , several times the cost of solving the system |
np.linalg.cond(A, 1) or np.inf | by forming inv(A) | and an unnecessary inverse |
scipy.linalg.lapack.dgecon | estimate of from existing LU | : nearly free if already factored |
scipy.linalg.solve | solves and estimates rcond with gecon | warns 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 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.
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 right to all four printed digits for and (the last column is , another norm, hence differs by factor 2). For , with , no float64 method can give the exact value (including np.linalg.cond, whose SVD calculates with absolute error of order , larger than itself), but both correctly say is of order 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
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What do you first write for ?
backward_error(A, b, x_hat, ord=2) returning (eta, dA, db): the Rigal-Gaches normwise backward error with , and perturbations dA, db attaining it: with and . ord can be 2 (2-norm and spectral norm) or np.inf (-norm and its operator norm, maximum row sum). If x_hat is the zero vector, the only input making it exact is : return , 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)Summary
- Relative condition number of problem is , or in the scalar case. It explodes when subtracting nearby numbers, for near 1, near poles and zeros, and multiple or clustered polynomial roots; Wilkinson showed roots suffice to reach .
- 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 are only stable; Cramer’s rule in and inverse multiplication give forward errors of order but are not backward stable.
- Forward error backward error . For linear systems backward error has closed form (Rigal and Gaches), and forward error is at most . A small residual certifies stability, not accuracy.
- Unstable algorithms often pass through a worse-conditioned subproblem: forward recurrence (error ), characteristic-polynomial coefficients, normal equations ().
- is estimated without forming the inverse:
geconin after LU, or SVD if accurate is needed.scipy.linalg.solvewarns;np.linalg.solvedoes not. Determinant measures none of this.