Direct linear solvers: pivoted LU and Cholesky
Study finite-precision LU and Cholesky, Wilkinson's backward-error analysis and pivoting, operation counts, banded systems, factor reuse and iterative refinement.
After this lesson you can
- Implement in-place partial-pivoting LU, forward and backward substitution, and Cholesky.
- Count factorization flops and predict scaling.
- State Gaussian elimination's backward-error bound and explain growth-factor effects.
- Solve multiple systems and compute log determinants reusing one factorization.
- Apply iterative refinement and predict when it improves accuracy.
- Choose SciPy solve, lu_factor, cho_factor or solve_banded for matrix structure.
Before you start
Motivation: a matrix that resists factorization
Solving is the most repeated operation in scientific computing. A Gaussian process needs and for each hyperparameter value; each Newton method iteration solves a Hessian system; an implicit simulation solves one per time step. In linear algebra you saw Gaussian elimination produce LU factorization and symmetric positive definite matrices admit Cholesky factorization. That was exact arithmetic. See what happens with a Gaussian-kernel matrix, the most common Gaussian-process covariance matrix, built on 200 points of :
import numpy as np
x = np.linspace(0, 1, 200)
K = np.exp(-(x[:, None] - x[None, :]) ** 2 / (2 * 0.3 ** 2)) # k(s, t) = exp(-(s - t)^2 / (2 * 0.3^2))
lam = np.linalg.eigvalsh(K)
print(f"autovalores calculados: máximo {lam[-1]:.4g}, mínimo {lam[0]:.3e}, negativos: {(lam < 0).sum()} de 200")
try:
np.linalg.cholesky(K)
except np.linalg.LinAlgError as e:
print("np.linalg.cholesky(K):", e)
print("np.linalg.det(K) =", np.linalg.det(K))
print("np.linalg.slogdet(K) =", np.linalg.slogdet(K))In exact arithmetic is positive definite: the Gaussian kernel on distinct points always produces a positive definite matrix. But the computer says otherwise. Cholesky refuses, determinant is exactly 0, 90 of 200 computed eigenvalues are negative (of order ), and slogdet returns log determinant with no meaning: it depends on rounding. On native NumPy with another LAPACK, the same cell gives and a negative sign: a negative determinant for a positive definite matrix. None of these routines has a programming error. This lesson explains why and what to do: what floating-point Gaussian elimination actually guarantees (Wilkinson’s analysis), why pivoting makes it reliable, why Cholesky needs no pivoting and when it fails, costs, band structure, why not to invert a matrix and how iterative refinement restores precision. It builds on backward stability, linear-system sensitivity and the forward error backward error bound.
Notation: is unit roundoff ( in float64, in float32) and the standard model is with . As in the previous two lessons, (assuming ). For matrices, is the matrix of absolute values and inequalities are entrywise.
Triangular systems
Every factorization ends with triangular systems, so start there. If is lower triangular with nonzero diagonal, equation of contains only , and solve in order:
This is forward substitution; back substitution for upper-triangular traverses rows bottom to top. Together they form forward and backward substitution. Row costs multiplications, subtractions and one division: floating-point operations (flops) total. A triangular system costs flops, like half a matrix-vector product.
Proof
For forward substitution, row evaluates by subtracting products one by one, then divides by . In the standard model each product carries its own factor and each subtraction another affecting everything accumulated so far; division adds one more. Moving the division factor across (if , then ) and dividing the equality by the product of subtraction factors accumulated by (leaving unperturbed) gives
where, counting factors, each is a product of at most factors (product retains its multiplication and receives inverses; the left side receives division and inverses). A product of such factors satisfies by the accumulation lemma in rounding errors. Define : since , .
∎Backward error is small entrywise: each coefficient of is perturbed relatively by at most , and zeros remain zero. Forward error is another story: triangular systems can be terribly ill conditioned. Viswanath and Trefethen (1998) showed that for triangular matrices with independent Gaussian entries almost surely: condition number grows like despite the innocent-looking matrix. The cell checks and measures both. Backward error uses the entrywise analogue of Rigal-Gaches, Oettli-Prager (1964), ; forward error is compared with 60-digit substitution.
import numpy as np
import mpmath as mp
def forward_sub(L, b, unit=False):
"""Resuelve L y = b con L triangular inferior (unit=True: diagonal de unos implícita)."""
n = len(b)
y = np.empty(n)
for i in range(n):
s = b[i] - L[i, :i] @ y[:i]
y[i] = s if unit else s / L[i, i]
return y
def back_sub(U, y):
"""Resuelve U x = y con U triangular superior."""
n = len(y)
x = np.empty(n)
for i in range(n - 1, -1, -1):
x[i] = (y[i] - U[i, i + 1:] @ x[i + 1:]) / U[i, i]
return x
u = 2.0 ** -53
mp.mp.dps = 60
def exacta(T, b): # la misma sustitución con 60 cifras
n = len(b)
Tm, bm = mp.matrix(T.tolist()), mp.matrix(b.tolist())
xe = [mp.mpf(0)] * n
for i in range(n):
xe[i] = (bm[i] - mp.fsum(Tm[i, j] * xe[j] for j in range(i))) / Tm[i, i]
return np.array([float(v) for v in xe])
rng = np.random.default_rng(0)
print(" n mediana kappa(T) mediana kappa^(1/n) máx omega/u máx error hacia delante mediana kappa*u")
for n in (10, 20, 30, 40):
ks, omegas, fwds = [], [], []
for _ in range(10): # 10 matrices de cada tamaño
T = np.tril(rng.standard_normal((n, n)))
b = rng.standard_normal(n)
xh = forward_sub(T, b)
omegas.append(np.max(np.abs(b - T @ xh) / (np.abs(T) @ np.abs(xh))))
xe = exacta(T, b)
fwds.append(np.max(np.abs(xh - xe)) / np.max(np.abs(xe)))
ks.append(np.linalg.cond(T))
k = np.median(ks)
print(f"{n:3d} {k:14.3e} {np.median(np.array(ks) ** (1 / n)):14.3f} {max(omegas) / u:12.2f}"
f" {max(fwds):18.2e} {k * u:16.2e}")Three observations. Condition number explodes: its median grows about three orders of magnitude whenever increases by 10, exactly as predicts, and decreases toward 2 (from 2.6 with to 2.1 with ). Backward error stays at one or two units of roundoff, as the theorem promises. Forward error is much smaller than : a worst-case bound is a bound, not a prediction. Higham devotes chapter 8 to this: substitution often yields more accurate solutions than suggests because its backward error is entrywise and respects structure, so an entrywise condition number matters, often much smaller than .
Gaussian elimination as
Recall the LU mechanism. Elimination step chooses pivot , computes multipliers for and updates each row by subtracting row times . In block form, with active matrix split into pivot, row, column and remainder,
is the Schur complement of , obtained by a rank-one update. If rows are swapped before each step to bring the chosen pivot into position, the result is with permutation matrix , unit lower triangular (its columns are vectors ) and upper triangular (its rows are pivots with their ). Two implementation details used by libraries:
- In place. Each multiplier is stored at , just zeroed by elimination. At the end, the matrix contains in its upper triangle and without its unit diagonal below: no extra matrix memory. The permutation is stored as an integer vector.
- Swaps apply to entire rows, including already stored multipliers. Thus the lower triangle finally is exactly the of .
Cost: counting flops
Step (from to ) calculates multipliers (divisions) and updates block with one multiplication and subtraction per entry:
This flop count says LU costs flops plus lower-order terms. Solving afterward costs two triangular systems, flops; Cholesky costs half LU: . Three practical consequences:
- Scaling. Doubling multiplies factorization time by 8 and solving with factors by 4. If factoring takes 10 ms on your machine, takes about 10 s.
- Factor once. With right-hand sides, factor-and-solve costs : for factorization dominates and extra right-hand sides are almost free.
- Flops are not time. Libraries reorganize elimination into blocks so most flops are matrix products (LAPACK routine
getrfon level-3 BLAS), reusing each cached datum many times. The flop count is unchanged; achieved flops per second change. Study this in the roofline lesson.
import numpy as np
import scipy.linalg as sl
def lu_inplace(A):
"""Eliminación con pivoteo parcial sobre una copia de A.
Devuelve (LU, perm): U en el triángulo superior, L (sin su diagonal de unos) en el inferior,
y perm[i] = fila original de A que ocupa la posición i, de modo que A[perm] = L U."""
A = np.array(A, dtype=float)
n = A.shape[0]
perm = np.arange(n)
for k in range(n - 1):
p = k + np.argmax(np.abs(A[k:, k])) # pivote: el mayor en módulo de la columna
if A[p, k] == 0.0:
raise np.linalg.LinAlgError(f"matriz singular: columna {k} nula bajo la diagonal")
if p != k:
A[[k, p]] = A[[p, k]] # filas enteras, multiplicadores incluidos
perm[[k, p]] = perm[[p, k]]
A[k + 1:, k] /= A[k, k] # multiplicadores: columna k de L
A[k + 1:, k + 1:] -= np.outer(A[k + 1:, k], A[k, k + 1:]) # actualización de rango uno
if A[n - 1, n - 1] == 0.0:
raise np.linalg.LinAlgError("matriz singular: último pivote nulo")
return A, perm
def lu_solve_mine(LU, perm, b):
y = forward_sub(LU, b[perm], unit=True) # L y = P b: la permutación va al lado derecho
return back_sub(LU, y)
rng = np.random.default_rng(1)
A = rng.standard_normal((300, 300))
b = rng.standard_normal(300)
LU, perm = lu_inplace(A)
L, U = np.tril(LU, -1) + np.eye(300), np.triu(LU)
print(f"max |A[perm] - L U| = {np.max(np.abs(A[perm] - L @ U)):.2e}")
print(f"max |l_ij| (pivoteo parcial: <= 1) = {np.max(np.abs(L)):.3f}")
lu_sp, piv = sl.lu_factor(A) # getrf de LAPACK: misma disposición in situ
perm_sp = np.arange(300)
for i, p in enumerate(piv): # piv[i] = fila con la que se intercambió la i (estilo LAPACK)
perm_sp[[i, p]] = perm_sp[[p, i]]
print("misma permutación que LAPACK:", np.array_equal(perm, perm_sp))
print(f"max |LU_mio - LU_lapack| = {np.max(np.abs(LU - lu_sp)):.2e}")
x = lu_solve_mine(LU, perm, b)
print(f"max |x_mio - x_lapack| = {np.max(np.abs(x - sl.lu_solve((lu_sp, piv), b))):.2e}")The custom factorization chooses the same pivots as getrf and produces the same factors up to rounding: LAPACK groups the same operations into blocks in another order. Notice LAPACK vector piv: it is not the permutation but a list of swaps ( is the row swapped with row at step ). Confusing them is a classic mistake.
Wilkinson’s error analysis
Is Gaussian elimination backward stable? Wilkinson’s early-1960s answer depends on one quantity and is the lesson’s central result.
Proof
Factors. Each entry of () is obtained by subtracting from , one by one, products with : exactly the substitution calculation with and no division. The previous proof’s argument gives except for factor on , with ; rearranging,
For , multiplier comes from taking , subtracting products with and dividing by ; the same calculation gives the inequality with sum through and . Since and the left sum is entry of , follows. Rank-one-update elimination performs exactly these subtractions in this order, so the bound applies.
Solution. By the substitution theorem, and with and . Multiplying gives with
where the last inequality is , following from applied twice.
∎Read this Gaussian elimination error analysis as follows: elimination is backward stable if and only if is not much greater than . It is never smaller (because ), but may be enormously larger: product can reconstruct of size 1 from mutually cancelling factors of size , and the theorem guarantees error of order times factor size, not size. Pivoting is about preventing factor growth.
Partial pivoting and growth factor
The tiny pivot
The smallest possible example shows everything. Let
The matrix is harmless: for small , . Without pivoting, the multiplier is and
If , floating-point : the 1 at position disappears, absorbed by a number times larger. Computed factors are exact for matrix , unlike : at entry , and has there, so the theorem’s bound holds comfortably without saying anything useful. Solving gives and : 100% error in a problem with . Swapping rows first gives pivot 1, multiplier , and a good result.
import numpy as np
def lu_nopivot(A):
A = np.array(A, dtype=float)
n = A.shape[0]
for k in range(n - 1):
A[k + 1:, k] /= A[k, k]
A[k + 1:, k + 1:] -= np.outer(A[k + 1:, k], A[k, k + 1:])
return A
b = np.array([1.0, 2.0])
for eps in (1e-4, 1e-10, 1e-20):
A = np.array([[eps, 1.0], [1.0, 1.0]])
LU = lu_nopivot(A)
L, U = np.tril(LU, -1) + np.eye(2), np.triu(LU)
x_sin = back_sub(U, forward_sub(L, b, unit=True))
LUp, perm = lu_inplace(A)
x_con = lu_solve_mine(LUp, perm, b)
x_exacta = np.array([1.0, 1.0 - 2.0 * eps]) / (1.0 - eps)
print(f"eps = {eps:.0e}: L U = {np.array2string(L @ U, precision=3).replace(chr(10), '')},"
f" error sin pivoteo {np.max(np.abs(x_sin - x_exacta)):.1e}, con pivoteo {np.max(np.abs(x_con - x_exacta)):.1e}")With unpivoted error is order ; with , ; with , total. Error grows like , exactly times factor size. The interactive does the same with matrix with condition number , showing the in-place matrix at each step.
The “information lost” readout, , is the theorem’s actually measured: without pivoting it grows like until, with , it is as large as entries of themselves. With pivoting enabled, the tiny-pivot row moves down and all multipliers have magnitude below 1. In float32 the same happens with pivots a billion times larger: suffices to lose everything.
Growth factor
The strategy of partial pivoting and growth factor is as simple as possible: at step choose as pivot the largest-magnitude entry in column among rows and move its row up. This guarantees : factor is controlled. The size of is measured by the
With partial pivoting, and , so , and summing rows Wilkinson’s theorem gives
Constant is pessimistic (Higham refines it in chapter 9, and observed backward error is typically order times a small constant); what matters is partial-pivoting elimination is backward stable exactly when is small. Is it always? Each step performs with , so maximum entry magnitude can at most double per step:
The bound is attained. The Wilkinson matrix has ones on the diagonal and last column, below the diagonal and zeros elsewhere. Every first-column entry has magnitude 1, so partial pivoting makes no swaps (choosing the first on ties), multipliers equal , and each step adds the pivot row’s entry to the last column: that column becomes .
import numpy as np
import scipy.linalg as sl
def wilkinson(n):
W = np.eye(n) - np.tril(np.ones((n, n)), -1)
W[:, -1] = 1.0
return W
def growth(A):
"""Factor de crecimiento de la eliminación con pivoteo parcial."""
A = np.array(A, dtype=float)
n = A.shape[0]
m0 = np.max(np.abs(A))
mx = m0
for k in range(n - 1):
p = k + np.argmax(np.abs(A[k:, k]))
A[[k, p]] = A[[p, k]]
A[k + 1:, k] /= A[k, k]
A[k + 1:, k + 1:] -= np.outer(A[k + 1:, k], A[k, k + 1:])
mx = max(mx, np.max(np.abs(A[k + 1:, k + 1:])))
return mx / m0
print("U de Wilkinson 5x5:\n", np.triu(lu_inplace(wilkinson(5))[0]))
rng = np.random.default_rng(2)
for n in (20, 40, 60):
W = wilkinson(n)
x = rng.standard_normal(n)
b = W @ x
xh = sl.solve(W, b) # getrf + getrs: eliminación con pivoteo parcial
eta = np.linalg.norm(b - W @ xh) / (np.linalg.norm(W, 2) * np.linalg.norm(xh) + np.linalg.norm(b))
print(f"n = {n}: rho = {growth(W):.3e} (2^(n-1) = {2.0 ** (n - 1):.3e}), kappa_2 = {np.linalg.cond(W):5.1f}, "
f"error hacia delante = {np.linalg.norm(xh - x) / np.linalg.norm(x):.1e}, error hacia atrás = {eta:.1e}")The Wilkinson matrix is well conditioned ( with ), yet partial-pivoting elimination, as in scipy.linalg.solve, loses digits at the rate of : with the solution has error (about ten digits lost), and with error is 17% and backward error is over times . With , exceeds : the theorem promises nothing. Partial-pivoting elimination is not backward stable in the previous lesson’s strict sense: its backward-error constant depends on , which may be exponential.
Why it rarely appears in practice
Yet it is the algorithm everyone has used for sixty years to solve dense systems. The reason is empirical and, recently, theoretical: matrices with large growth are extremely rare.
For Gaussian matrices median rises only from 1.3 with to 6 with , and the maximum of 200 samples at is 10; worst case is . With signs values are higher (median 25 at ), but still far from worst case. The distribution difference is mainly normalization: divides by the largest entry of , which with signs is 1 and with unit-variance Gaussians much larger (around 4 for ). The next cell measures this in Python with two literature normalizations:
import numpy as np
rng = np.random.default_rng(3)
print(" n mediana rho máximo rho mediana de max|a^(k)| / sigma n^(2/3)")
for n, muestras in ((8, 100), (16, 100), (32, 60), (64, 30), (128, 20)):
rhos, absol = [], []
for _ in range(muestras):
A = rng.standard_normal((n, n)) # sigma = 1
r = growth(A)
rhos.append(r)
absol.append(r * np.max(np.abs(A)))
print(f"{n:4d} {np.median(rhos):10.2f} {np.max(rhos):10.2f} {np.median(absol):20.2f} {n ** (2 / 3):14.2f}")
W60 = wilkinson(60)
print("\nWilkinson 60x60 + ruido gaussiano de desviación 1e-12, cinco veces:",
[round(float(growth(W60 + 1e-12 * rng.standard_normal((60, 60)))), 4) for _ in range(5)])The first column normalizes by the largest entry of , as in the definition; the third by entry standard deviation (), as Trefethen and Schreiber used in Average-case stability of Gaussian elimination (1990). They found that across distributions and , mean growth is within a few percentage points of ; the cell’s median with far fewer samples fits as well. The difference between first and third columns is only the largest of Gaussians, growing roughly like (about 4.4 for ). Three facts complete the picture:
- It is a measure phenomenon. Huang and Tikhomirov (2022) proved that for Gaussian matrices partial-pivoting growth factor is bounded by a polynomial in with probability near 1. Exponential-growth matrices exist, but form a tiny set.
- It is not impossible in real problems. Wright (1993) found systems from multiple-shooting boundary-value discretization with exponential growth, and Foster (1994) others from Volterra integral equations. They are rare but exist, so check residuals (as in iterative refinement).
- The Wilkinson matrix is fragile. Growth depends on all pivot candidates tying in magnitude and the first always winning. The cell’s last line shows adding Gaussian noise of deviation breaks ties and growth falls from to 2.
Costlier strategies offer stronger guarantees. Complete pivoting searches the entire active submatrix for its largest entry (swapping rows and columns), adding comparisons; Wilkinson proved growth bounded by a function slower than any exponential, of order . Rook pivoting seeks an entry maximal in its row and column, at intermediate cost. In practice LAPACK uses partial pivoting for general dense matrices and complete pivoting is paid for mainly to reveal rank.
Cholesky in finite precision
If is symmetric positive definite, with lower-triangular having positive diagonal. Equating column on both sides gives the column-by-column algorithm:
By symmetry only half the products are computed and stored, costing flops (plus square roots): half of LU. The radicand of is the Gaussian-elimination pivot, entry of the Schur complement, positive exactly when the matrix is positive definite: in exact arithmetic Cholesky finishes if and only if is positive definite.
Why it needs no pivoting
The diagonal equation says more. Since is a sum of squares,
No factor entry can exceed the square root of its corresponding diagonal, without any pivoting. (You will prove this in the guided exercise, along with non-growth of intermediate matrices.) Cholesky’s analogue of Wilkinson’s theorem (Higham, chapter 10) says that if the algorithm finishes, with . The dangerous term is bounded by Cauchy-Schwarz:
Thus (for computed factors, up to terms of order ): backward error is bounded by the matrix itself, without a growth factor. In 2-norm, , because . This is finite-precision Cholesky stability and jitter: Cholesky is unconditionally backward stable and costs half as much. For a symmetric positive definite matrix there is no reason to use LU.
The interactive shows factorization geometry: is a square root of deforming the unit sphere into the ellipsoid of , making it the tool for sampling multivariate normals ( with ). It also shows failure: the algorithm does not “know” the matrix is not positive definite until finding a negative radicand, exactly when Schur complement ceases to be positive, i.e. when .
Failure as a numerical test and jitter
This makes Cholesky the cheapest way to check whether a symmetric matrix is positive definite: attempt factorization ( flops versus several for eigenvalues). In floating point the question changes. Backward error is order , so the algorithm works with a matrix indistinguishable from ; if is below that noise, the matrix is effectively semidefinite in float64 and Cholesky may fail or finish depending on rounding. (Demmel in 1989 gave the precise sufficient condition for completion: of the unit-diagonal-rescaled matrix greater than an amount of order .) This happened in the motivation: Gaussian-kernel eigenvalues decay exponentially, hundreds fall below , and the matrix is singular in float64.
The usual solution is jitter: factor with small . It raises every eigenvalue by and brings condition number to . But it changes the problem: you solve another system and compute another matrix’s log determinant, , potentially very different when many are below . In a Gaussian process is interpreted as added observation noise (the “nugget”); use the smallest working amount relative to diagonal scale and acknowledge it. Scikit-learn, for example, adds alpha=1e-10 to the diagonal by default in GaussianProcessRegressor.
import numpy as np
import scipy.linalg as sl
def cholesky(A):
"""Factor de Cholesky L (A = L L^T), columna a columna. Lanza LinAlgError si un radicando es <= 0."""
A = np.asarray(A, dtype=float)
n = A.shape[0]
L = np.zeros_like(A)
for j in range(n):
d = A[j, j] - L[j, :j] @ L[j, :j]
if not d > 0:
raise np.linalg.LinAlgError(f"no es definida positiva: radicando {d:.3e} en la columna {j}")
L[j, j] = np.sqrt(d)
L[j + 1:, j] = (A[j + 1:, j] - L[j + 1:, :j] @ L[j, :j]) / L[j, j]
return L
rng = np.random.default_rng(4)
B = rng.standard_normal((300, 300))
S = B @ B.T + 300 * np.eye(300)
Lm = cholesky(S)
c, lower = sl.cho_factor(S, lower=True) # potrf; el otro triángulo de c no se usa
print(f"max |L_mio - L_cho_factor| = {np.max(np.abs(Lm - np.tril(c))):.2e}")
print(f"max_ij |l_ij| / sqrt(a_ii) = {np.max(np.abs(Lm) / np.sqrt(np.diag(S))[:, None]):.4f}")
try:
cholesky(K)
except np.linalg.LinAlgError as e:
print("\nnúcleo gaussiano de la motivación:", e)
print("\n jitter ¿factoriza? log det(K + jitter I)")
for d in (1e-16, 1e-15, 1e-14, 1e-12, 1e-10, 1e-8, 1e-6):
try:
Lk = cholesky(K + d * np.eye(200))
print(f"{d:8.0e} sí {2 * np.sum(np.log(np.diag(Lk))):10.1f}")
except np.linalg.LinAlgError:
print(f"{d:8.0e} no")
# con ruido de observación de verdad (sigma^2 = 1e-4) el jitter apenas importa
print("\ncon ruido sigma^2 = 1e-4 en la diagonal:")
for d in (0.0, 1e-10, 1e-8):
Lk = cholesky(K + (1e-4 + d) * np.eye(200))
print(f" jitter {d:7.0e}: log det = {2 * np.sum(np.log(np.diag(Lk))):.6f}")The implementation matches LAPACK up to rounding and bound holds (maximum ratio exactly 1, at ). With the Gaussian kernel, the radicand becomes negative already at column 5. Minimum working jitter here is , rounding-noise level, but observe the last column: between and log determinant changes by about 3400 nats because 190 of 200 exact eigenvalues of are below and each contributes . Jitter would dominate a maximized likelihood. With realistic observation noise , all eigenvalues exceed (), factorization needs no jitter and the effect of is first-order : adding changes the fourth decimal of log determinant and the second. Jitter patches rounding; it does not replace the model’s noise term.
Banded and tridiagonal matrices
Many large matrices have almost all entries zero, with nonzeros concentrated near the diagonal. Discretizing on a grid of points with finite differences gives the tridiagonal matrix ; cubic splines, smoothing filters and the implicit Crank–Nicolson scheme for the heat equation give tridiagonal or pentadiagonal matrices. A matrix has lower bandwidth and upper bandwidth if when or .
The key observation is that elimination without pivoting creates no entries outside the band: step only touches rows (the only ones with ) and columns within them. Thus has lower bandwidth and upper bandwidth , and the cost is instead of : about flops. With partial pivoting, swaps can bring up rows with more entries, and the upper bandwidth of becomes ; the cost remains linear in .
For a tridiagonal matrix () with subdiagonal , diagonal and superdiagonal , elimination without pivoting is the Thomas algorithm:
That takes about flops: linear time. The denominator is the pivot , and the usual question is whether it can be tiny. It cannot in the two cases covering almost all applications: if is symmetric positive definite (this is Cholesky in disguise, and the previous section’s argument applies) or diagonally dominant by rows or columns, in which case elimination without pivoting has (Wilkinson). The finite-difference matrix has both properties. These banded systems and the Thomas algorithm explain why implicit methods for one-dimensional partial differential equations are as cheap as explicit ones.
import time
import numpy as np
import scipy.linalg as sl
def thomas(a, b, c, d):
"""Resuelve un sistema tridiagonal: a subdiagonal (n-1), b diagonal (n), c superdiagonal (n-1)."""
a, b, c, d = (list(map(float, v)) for v in (a, b, c, d)) # listas: el bucle es Python puro
n = len(b)
cp, dp = [0.0] * n, [0.0] * n
cp[0], dp[0] = (c[0] / b[0] if n > 1 else 0.0), d[0] / b[0]
for i in range(1, n):
piv = b[i] - a[i - 1] * cp[i - 1] # pivote u_ii
cp[i] = c[i] / piv if i < n - 1 else 0.0
dp[i] = (d[i] - a[i - 1] * dp[i - 1]) / piv
x = [0.0] * n
x[-1] = dp[-1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return np.array(x)
def poisson(n): # tridiag(-1, 2, -1)
return -np.ones(n - 1), 2 * np.ones(n), -np.ones(n - 1)
n = 1000
a, bdiag, c = poisson(n)
d = np.random.default_rng(5).standard_normal(n)
ab = np.vstack([np.r_[0.0, c], bdiag, np.r_[a, 0.0]]) # formato de banda de LAPACK: ab[1 + i - j, j] = A[i, j]
x_t = thomas(a, bdiag, c, d)
x_b = sl.solve_banded((1, 1), ab, d)
x_d = np.linalg.solve(np.diag(bdiag) + np.diag(a, -1) + np.diag(c, 1), d)
print(f"max |thomas - solve_banded| = {np.max(np.abs(x_t - x_b)):.2e}, max |thomas - denso| = {np.max(np.abs(x_t - x_d)):.2e}")
for n in (20_000, 200_000):
a, bdiag, c = poisson(n)
d = np.ones(n)
t0 = time.perf_counter(); thomas(a, bdiag, c, d); t1 = time.perf_counter()
print(f"Thomas en Python puro, n = {n:7d}: {t1 - t0:.3f} s")
for n in (200_000, 2_000_000):
a, bdiag, c = poisson(n)
ab = np.vstack([np.r_[0.0, c], bdiag, np.r_[a, 0.0]])
t0 = time.perf_counter(); sl.solve_banded((1, 1), ab, np.ones(n)); t1 = time.perf_counter()
print(f"solve_banded (LAPACK gtsv), n = {n:7d}: {t1 - t0:.3f} s")Thomas in pure Python agrees with LAPACK and the dense solution to , the level for this matrix (), and multiplying by 10 multiplies its time by about 10: it is linear. solve_banded solves two million unknowns in a fraction of a second; the dense version would need TB just to store the matrix.
Beyond the band: fill-in
The structure elimination preserves is not merely sparsity but the pattern. When eliminating variable , every row with a nonzero in column receives a multiple of row , and every pair of neighbors of becomes connected. Zero entries of that become nonzero in are called fill-in. An arrow matrix, with the diagonal and a single dense row and column, is the extreme example:
With the dense row first, the first step connects all variables and becomes completely full: nonzeros and flops. With the same matrix and unknowns in another order (the dense variable last), there is no fill-in: nonzeros and flops. Symmetrically reordering rows and columns, , does not change the solution (only its order), and can change the cost from cubic to linear. Choosing that permutation is a combinatorial problem (finding minimum fill is NP-hard) that programs solve using heuristics such as minimum degree or nested dissection. You will revisit it in sparse Cholesky factorization, in the iterative methods lesson.
Never invert a matrix
Writing on paper is correct; writing np.linalg.inv(A) @ b in a program almost never is. There are two reasons.
Cost. Forming costs about flops with LAPACK’s dedicated routine (getri, which exploits the factors’ structure) and if is solved by brute force, as np.linalg.inv does. Solving one system costs . For one right-hand side, the inverse costs three to four times as many flops and gains nothing: multiplying by costs , the same as solving with the computed factors.
Accuracy. You saw this in the previous lesson’s stability map: with has forward error similar to elimination, but its residual is of order : it is not backward stable.
The same applies to the determinant. follows from LU at no extra cost, , with the permutation’s sign (the parity of the number of swaps); with Cholesky, . But the product of numbers readily overflows or underflows: the determinant of is , which cannot be represented in float64. What is almost always needed is the log-determinant:
This is how np.linalg.slogdet and the log-likelihood of any multivariate normal work, as the next laboratory section shows.
Iterative refinement
Suppose you already have the factors and a solution . Its residual satisfies : the error is the solution of another system with the same matrix. Solving it using the factors you already have ( flops) and adding the correction gives iterative refinement:
Why does it not always give the exact solution in one step? Because the factors belong to , not . If the operations in the step were exact, , and therefore
At each step the error is multiplied by a matrix with norm
where is the unit roundoff of the precision used for factorization. Refinement converges linearly, with a rate bounded by something of order , if is clearly less than 1. This is a sufficient worst-case condition: in practice the rate is often smaller, as you will soon see. How far does it converge? Until errors ignored in the calculation above dominate: the residual error, computed with unit , and the error in the sum , with unit . Roughly (Higham, chapter 12), the final error is of order . This gives three uses of iterative refinement:
- Classical (Wilkinson, Moler 1967): factor in working precision and compute the residual in double precision, . The final error falls to , independent of , provided .
- Fixed precision (): it does not improve forward error beyond , but Skeel (1980) proved that a single step makes backward error small entry by entry, fixing poorly scaled systems.
- Mixed precision: factor in low precision (float32 or less), which is much faster, and compute the residual and update in float64. With it converges if , and the result has the accuracy of float64 elimination () for the price of a float32 factorization. Langou and coauthors popularized it in 2006, and it is LAPACK’s
dsgesvroutine. With GPU tensor units, which factor in float16 or bfloat16 at much higher speeds, it underpins mixed-precision refinement in the frontier lesson.
The interactive shows both theoretical predictions and a nuance. The blue curve stops at , the level of float64 elimination, as the bound with says; the orange curve, without extra residual precision, stays at from the first iteration: refinement in the same precision does not improve forward error. Observed contraction grows in proportion to , but is 15 to 30 times smaller: per step with , with , with and with , where and iteration still converges, slowly. With it diverges. The bound assumes points in the worst possible direction, which factorization roundoff does not; the threshold’s order of magnitude, , remains unchanged.
Lab: from scratch versus LAPACK
You now have the pieces: forward_sub, back_sub, lu_inplace, cholesky and thomas. Two claims remain to be measured: that cost scales as and that inversion is more expensive and less reliable than solving.
import time
import numpy as np
import scipy.linalg as sl
def mejor_tiempo(f, rep=3):
t = []
for _ in range(rep):
t0 = time.perf_counter(); f(); t.append(time.perf_counter() - t0)
return min(t)
rng = np.random.default_rng(6)
prev = None
print(" n lu_inplace (s) cociente lu_factor (s) cociente")
for n in (100, 200, 400, 800):
A = rng.standard_normal((n, n))
t_mio = mejor_tiempo(lambda: lu_inplace(A), rep=1 if n == 800 else 2)
t_lap = mejor_tiempo(lambda: sl.lu_factor(A))
if prev:
print(f"{n:4d} {t_mio:12.4f} {t_mio / prev[0]:8.1f} {t_lap:12.4f} {t_lap / prev[1]:8.1f}")
else:
print(f"{n:4d} {t_mio:12.4f} {'':8s} {t_lap:12.4f}")
prev = (t_mio, t_lap)The ratio when doubling rises toward 8 as grows (platform checker runs produced 6.6 to 7.7 when going from 400 to 800; browser times vary from run to run). At small sizes it stays below this because non-cubic costs (the Python loop of lu_inplace, which performs iterations, and call overhead) still matter. Note also the roughly tenfold factor between the two columns: the same flops execute much faster when arranged in blocks that reuse the cache.
import time
import numpy as np
import scipy.linalg as sl
def matriz_con_kappa(n, kappa, seed):
r = np.random.default_rng(seed)
U, _ = np.linalg.qr(r.standard_normal((n, n)))
V, _ = np.linalg.qr(r.standard_normal((n, n)))
return (U * kappa ** (-np.arange(n) / (n - 1))) @ V.T
n = 500
A = matriz_con_kappa(n, 1e10, 7)
x = np.random.default_rng(8).standard_normal(n)
b = A @ x
t_solve = mejor_tiempo(lambda: np.linalg.solve(A, b))
t_inv = mejor_tiempo(lambda: np.linalg.inv(A) @ b)
nA = np.linalg.norm(A, 2)
for nombre, xh, t in (("solve", np.linalg.solve(A, b), t_solve), ("inv(A) @ b", np.linalg.inv(A) @ b, t_inv)):
fwd = np.linalg.norm(xh - x) / np.linalg.norm(x)
eta = np.linalg.norm(b - A @ xh) / (nA * np.linalg.norm(xh) + np.linalg.norm(b))
print(f"{nombre:11s}: {t:.4f} s, error hacia delante {fwd:.1e}, error hacia atrás {eta / 2**-53:8.1f} u")
print(f"cociente de tiempos inv / solve = {t_inv / t_solve:.1f} (cociente de flops con A X = I: (8/3) / (2/3) = 4)")With , both solutions have forward errors of order or less (larger for the inverse), but the inverse has backward error hundreds of millions of times larger than (it grows with , as you saw previously), and takes about three times longer. The time ratio need not be exactly 4: flops predict scaling, not time, because routines use memory differently, and browser measurements for matrices of this size are noisy. There is no case where inv(A) @ b is better than solve(A, b). Computing is justified only when its entries are needed (for example, the diagonal of a posterior covariance matrix), and even then shortcuts often exist.
Lab: refinement and log-determinants
First, mixed-precision refinement with SciPy routines: lu_factor on a float32 matrix calls sgetrf, LAPACK’s single-precision LU, and lu_solve with those factors solves in float32. Residual and update use float64.
import numpy as np
import scipy.linalg as sl
n = 200
rng = np.random.default_rng(9)
print(" kappa error de cada iteración (relativo, norma inf) solve en float64")
for lk in (2, 4, 6, 7, 8):
A = matriz_con_kappa(n, 10.0 ** lk, lk)
x = rng.standard_normal(n)
b = A @ x
lu32 = sl.lu_factor(A.astype(np.float32)) # sgetrf: factorización en float32
xk = sl.lu_solve(lu32, b.astype(np.float32)).astype(np.float64)
errs = [np.max(np.abs(xk - x)) / np.max(np.abs(x))]
for _ in range(8):
r = b - A @ xk # residuo en float64
d = sl.lu_solve(lu32, r.astype(np.float32)) # corrección con los factores de float32
xk = xk + d # actualización en float64
errs.append(np.max(np.abs(xk - x)) / np.max(np.abs(x)))
x64 = sl.solve(A, b)
print(f" 1e{lk} " + " ".join(f"{e:.0e}" for e in errs) + f" {np.max(np.abs(x64 - x)) / np.max(np.abs(x)):.0e}")Read each row from left to right. With , two iterations suffice to reach float64 level. With and more steps are needed, each dividing the error by a factor following with a favorable constant: about times with (), and about 100 with (). Finally the solution has the same error as solve in float64. With , is no longer small, but for these matrices actual contraction is 0.05 to 0.1 per step and iteration still converges slowly; with () it stalls at error of order 0.1. Theory predicts the threshold’s order of magnitude well, not its exact value: the constant depends on the matrix. Here error is measured against the used to construct , so it includes rounding error in , of order : that is the floor for refinement and solve.
Next, the log-determinant. The log-likelihood of is
and with the two difficult terms come from the same factorization: (forward substitution) and . This is how a Gaussian process evaluates its log-likelihood.
import numpy as np
import scipy.linalg as sl
n = 400
t = np.linspace(0, 10, n)
Sigma = np.exp(-(t[:, None] - t[None, :]) ** 2 / 2) + 0.01 * np.eye(n) # núcleo gaussiano + ruido
L = cholesky(Sigma)
y = L @ np.random.default_rng(10).standard_normal(n) # una muestra de N(0, Sigma)
def loglik(y, L):
z = forward_sub(L, y) # z = L^{-1} y
return -0.5 * z @ z - np.sum(np.log(np.diag(L))) - 0.5 * len(y) * np.log(2 * np.pi)
print("np.linalg.det(Sigma) =", np.linalg.det(Sigma))
print("np.linalg.det(1e3 * Sigma) =", np.linalg.det(1e3 * Sigma))
print(f"log det por Cholesky = {2 * np.sum(np.log(np.diag(L))):.6f}")
print(f"np.linalg.slogdet = {np.linalg.slogdet(Sigma)[1]:.6f}")
print(f"log p(y) con Cholesky = {loglik(y, L):.6f}")
c_and_lower = sl.cho_factor(Sigma, lower=True)
ref = -0.5 * y @ sl.cho_solve(c_and_lower, y) - np.sum(np.log(np.diag(c_and_lower[0]))) - 0.5 * n * np.log(2 * np.pi)
print(f"log p(y) con cho_factor = {ref:.6f}")The direct determinant underflows (it is ) and, scaling the matrix by , overflows to infinity; the Cholesky log-determinant is a well-behaved four-digit number and agrees with slogdet. The log-likelihood never uses or .
In libraries
| Situation | SciPy | What it calls |
|---|---|---|
| One general system | scipy.linalg.solve(A, b) or np.linalg.solve | gesv: LU with partial pivoting and substitutions |
| Many right-hand sides arriving separately | lu, piv = lu_factor(A) then lu_solve((lu, piv), b) | getrf once, getrs () each time |
| Symmetric positive definite | c = cho_factor(A), cho_solve(c, b), or solve(A, b, assume_a="pos") | potrf and potrs: Cholesky, half the flops |
| Banded | solve_banded((p, q), ab, b); if also positive definite, solveh_banded | gbsv, pbsv, gtsv |
| Explicit factors | P, L, U = scipy.linalg.lu(A) (convention ) | getrf and reconstruction |
| Direct access | scipy.linalg.lapack.dgetrf, dpotrf | LAPACK without wrapper |
Three useful details. solve with assume_a=None, the default in recent SciPy, inspects the matrix for structure (symmetry, triangular or banded form) and chooses a routine; if you already know it is positive definite, specify assume_a="pos" to skip inspection. scipy.linalg.lu uses convention , opposite to in textbooks: to solve, apply to the right-hand side. And lu_factor returns LAPACK swaps, not the permutation.
import time
import numpy as np
import scipy.linalg as sl
n, k = 100, 200
rng = np.random.default_rng(11)
A = rng.standard_normal((n, n))
B = rng.standard_normal((n, k))
t0 = time.perf_counter()
X1 = np.column_stack([sl.solve(A, B[:, j]) for j in range(k)]) # 200 factorizaciones
t1 = time.perf_counter()
fac = sl.lu_factor(A) # una factorización...
X2 = np.column_stack([sl.lu_solve(fac, B[:, j]) for j in range(k)]) # ... y 200 sustituciones
t2 = time.perf_counter()
print(f"solve en un bucle: {t1 - t0:.3f} s; lu_factor + lu_solve: {t2 - t1:.3f} s; misma solución: {np.allclose(X1, X2)}")
# el error de olvidar la permutación con el convenio A = P L U de scipy.linalg.lu
P, L, U = sl.lu(A)
b = B[:, 0]
x_bien = sl.solve_triangular(U, sl.solve_triangular(L, P.T @ b, lower=True, unit_diagonal=True))
x_mal = sl.solve_triangular(U, sl.solve_triangular(L, b, lower=True, unit_diagonal=True))
print(f"con P^T b: residuo {np.linalg.norm(A @ x_bien - b):.1e}; sin P: residuo {np.linalg.norm(A @ x_mal - b):.1e}")
print("solve con assume_a='pos' en una matriz SPD:", np.allclose(sl.solve(A @ A.T + n * np.eye(n), b, assume_a="pos"),
np.linalg.solve(A @ A.T + n * np.eye(n), b)))In PyTorch, torch.linalg.solve, torch.linalg.lu_factor and torch.linalg.lu_solve, torch.linalg.cholesky and torch.cholesky_solve do the same on a GPU and in matrix batches; torch.linalg.cholesky_ex returns an error code instead of raising an exception, useful in a training loop trying increasing jitters.
Common mistakes
Exercises
Step 1 of 4. What relation does entry of give?
solve_spd(A, b) to solve for symmetric positive definite using Cholesky and two substitutions, without `np.linalg` or `scipy.linalg` (NumPy operations such as @, np.sqrt and slicing are allowed). Raise ValueError with a clear message if is not square, is not symmetric (relative tolerance on ), or a Cholesky radicand is (not positive definite at working precision). b may be a vector or a matrix with several columns.import numpy as np
def solve_spd(A, b):
"""Resuelve A x = b con A simétrica definida positiva, por Cholesky."""
A = np.asarray(A, dtype=float)
b = np.asarray(b, dtype=float)
# tu código: comprobaciones, factor L columna a columna, L y = b, L^T x = y
return np.zeros_like(b)slogdet_lu(A) returning (sign, logabsdet) like np.linalg.slogdet: the determinant sign (, , or if singular) and ( if singular). Use your own elimination with partial pivoting (no np.linalg.det, slogdet or scipy.linalg): the sign is the product of pivot signs times , and the logarithm is the sum of . It must work when the determinant overflows or underflows in float64.import numpy as np
def slogdet_lu(A):
"""Devuelve (sign, logabsdet) de A mediante LU con pivoteo parcial."""
A = np.array(A, dtype=float)
n = A.shape[0]
# tu código
return 1.0, 0.0Summary
- Triangular systems cost flops and substitution is entrywise backward stable, although triangular matrices may be very ill conditioned.
- LU costs flops, Cholesky and solving with the factors : factor once and reuse. The flop count predicts scaling ( when doubling ), not absolute time.
- Without pivoting, a pivot produces multipliers that erase matrix information. With partial pivoting and ; Wilkinson’s matrix reaches the bound, but for random matrices grows as a small power of .
- Cholesky is backward stable without pivoting (); failure tests positive definiteness in working precision, and jitter avoids it by changing the problem: keep it small and remember it changes the log-determinant.
- Banded matrices factor in and tridiagonal ones in using Thomas; in sparse matrices variable ordering determines fill.
- Never form to solve: it costs more and is not backward stable. The log-determinant comes from the diagonal of or without overflow.
- Iterative refinement converges at a rate proportional to (smaller in practice) and reaches error : factor in float32 and refine in float64 for float64 accuracy if .