Module contents
Lesson 4 of 26Core 105 min

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 Ax=b\mat{A}\vb{x} = \vb{b} is the most repeated operation in scientific computing. A Gaussian process needs K−1y\mat{K}\inv\vb{y} and log⁡det⁡K\log\det\mat{K} 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 [0,1][0, 1]:

[ ]A Gaussian kernel that resists factorizationBrowser
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 K\mat{K} 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 10−1410^{-14}), and slogdet returns log determinant −6669-6669 with no meaning: it depends on rounding. On native NumPy with another LAPACK, the same cell gives −6447-6447 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 ≲κ⋅\lesssim \kappa\cdot backward error bound.

Notation: uu is unit roundoff (2−53≈1.1×10−162^{-53} \approx 1.1\times 10^{-16} in float64, 2−24≈6×10−82^{-24} \approx 6\times 10^{-8} in float32) and the standard model is fl⁡(a∘b)=(a∘b)(1+δ)\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta) with ∣δ∣≤u\abs{\delta} \le u. As in the previous two lessons, γn=nu/(1−nu)\gamma_n = nu/(1 - nu) (assuming nu<1nu < 1). For matrices, ∣A∣\abs{\mat{A}} is the matrix of absolute values and inequalities are entrywise.

Triangular systems

Every factorization ends with triangular systems, so start there. If L\mat{L} is lower triangular with nonzero diagonal, equation ii of Ly=b\mat{L}\vb{y} = \vb{b} contains only y1,…,yiy_1, \dots, y_i, and solve yiy_i in order:

yi=1lii(bi−∑j=1i−1lij yj),i=1,…,n.y_i = \frac{1}{l_{ii}}\Big(b_i - \sum_{j=1}^{i-1} l_{ij}\,y_j\Big), \qquad i = 1, \dots, n.

This is forward substitution; back substitution for upper-triangular U\mat{U} traverses rows bottom to top. Together they form forward and backward substitution. Row ii costs i−1i - 1 multiplications, i−1i - 1 subtractions and one division: ∑i=1n(2i−1)=n2\sum_{i=1}^{n}(2i - 1) = n^2 floating-point operations (flops) total. A triangular system costs n2n^2 flops, like half a matrix-vector product.

Proof

For forward substitution, row ii evaluates c=bi−∑j<ilijy^jc = b_i - \sum_{j<i} l_{ij}\hat y_j by subtracting products one by one, then divides by liil_{ii}. In the standard model each product lijy^jl_{ij}\hat y_j carries its own factor (1+δ)(1 + \delta) and each subtraction another affecting everything accumulated so far; division adds one more. Moving the division factor across (if y^i=(c/lii)(1+δ)\hat y_i = (c/l_{ii})(1 + \delta), then liiy^i(1+δ)−1=cl_{ii}\hat y_i (1 + \delta)^{-1} = c) and dividing the equality by the product of i−1i - 1 subtraction factors accumulated by bib_i (leaving bib_i unperturbed) gives

lii y^i (1+θii)=bi−∑j<ilij y^j (1+θij),l_{ii}\,\hat y_i\,(1 + \theta_{ii}) = b_i - \sum_{j<i} l_{ij}\,\hat y_j\,(1 + \theta_{ij}),

where, counting factors, each 1+θ1 + \theta is a product of at most ii factors (1+δ)±1(1 + \delta)^{\pm 1} (product jj retains its multiplication and receives j−1j - 1 inverses; the left side receives division and i−1i - 1 inverses). A product of kk such factors satisfies ∣θ∣≤γk\abs{\theta} \le \gamma_k by the accumulation lemma in rounding errors. Define (ΔT)ij=θij lij(\Delta\mat{T})_{ij} = \theta_{ij}\,l_{ij}: since i≤ni \le n, ∣θij∣≤γi≤γn\abs{\theta_{ij}} \le \gamma_i \le \gamma_n.

∎

Backward error is small entrywise: each coefficient of T\mat{T} is perturbed relatively by at most γn≈nu\gamma_n \approx nu, 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 κn1/n→2\kappa_n^{1/n} \to 2 almost surely: condition number grows like 2n2^n despite the innocent-looking matrix. The cell checks and measures both. Backward error uses the entrywise analogue of Rigal-Gaches, Oettli-Prager (1964), ω=max⁡i∣ri∣/(∣T∣∣x^∣)i\omega = \max_i \abs{r_i}/(\abs{\mat{T}}\abs{\hat{\vb{x}}})_i; forward error is compared with 60-digit substitution.

[ ]Forward and backward substitution from scratchBrowser
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 nn increases by 10, exactly as 210≈1032^{10} \approx 10^3 predicts, and κ1/n\kappa^{1/n} decreases toward 2 (from 2.6 with n=10n = 10 to 2.1 with n=40n = 40). Backward error stays at one or two units of roundoff, as the theorem promises. Forward error is much smaller than κu\kappa u: a worst-case bound is a bound, not a prediction. Higham devotes chapter 8 to this: substitution often yields more accurate solutions than κ\kappa suggests because its backward error is entrywise and respects structure, so an entrywise condition number matters, often much smaller than κ\kappa.

Gaussian elimination as PA=LU\mat{P}\mat{A} = \mat{L}\mat{U}

Recall the LU mechanism. Elimination step kk chooses pivot akk(k)≠0a^{(k)}_{kk} \neq 0, computes multipliers lik=aik(k)/akk(k)l_{ik} = a^{(k)}_{ik}/a^{(k)}_{kk} for i>ki > k and updates each row ii by subtracting row kk times likl_{ik}. In block form, with active matrix A(k)\mat{A}^{(k)} split into pivot, row, column and remainder,

A(k)=[αw⊤vB]⟹l=v/α,A(k+1)=B−l w⊤.\mat{A}^{(k)} = \begin{bmatrix} \alpha & \vb{w}\T \\ \vb{v} & \mat{B} \end{bmatrix} \quad\Longrightarrow\quad \vb{l} = \vb{v}/\alpha, \qquad \mat{A}^{(k+1)} = \mat{B} - \vb{l}\,\vb{w}\T.

A(k+1)\mat{A}^{(k+1)} is the Schur complement of α\alpha, obtained by a rank-one update. If rows are swapped before each step to bring the chosen pivot into position, the result is PA=LU\mat{P}\mat{A} = \mat{L}\mat{U} with permutation matrix P\mat{P}, unit lower triangular L\mat{L} (its columns are vectors l\vb{l}) and upper triangular U\mat{U} (its rows are pivots with their w⊤\vb{w}\T). Two implementation details used by libraries:

  • In place. Each multiplier likl_{ik} is stored at (i,k)(i, k), just zeroed by elimination. At the end, the matrix contains U\mat{U} in its upper triangle and L\mat{L} 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 L\mat{L} of PA=LU\mat{P}\mat{A} = \mat{L}\mat{U}.

Cost: counting flops

Step kk (from 11 to n−1n - 1) calculates n−kn - k multipliers (divisions) and updates block (n−k)×(n−k)(n - k)\times(n - k) with one multiplication and subtraction per entry:

∑k=1n−1[2(n−k)2+(n−k)]=2∑m=1n−1m2+∑m=1n−1m=2n33−n22−n6.\sum_{k=1}^{n-1}\Big[2(n - k)^2 + (n - k)\Big] = 2\sum_{m=1}^{n-1} m^2 + \sum_{m=1}^{n-1} m = \frac{2n^3}{3} - \frac{n^2}{2} - \frac{n}{6}.

This flop count says LU costs 23n3\frac{2}{3}n^3 flops plus lower-order terms. Solving afterward costs two triangular systems, 2n22n^2 flops; Cholesky costs half LU: 13n3\frac{1}{3}n^3. Three practical consequences:

  • Scaling. Doubling nn multiplies factorization time by 8 and solving with factors by 4. If factoring 1000×10001000\times 1000 takes 10 ms on your machine, 10 000×10 00010\,000\times 10\,000 takes about 10 s.
  • Factor once. With kk right-hand sides, factor-and-solve costs 23n3+2kn2\frac{2}{3}n^3 + 2kn^2: for k≪nk \ll n 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 getrf on 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.
[ ]In-place LU with partial pivotingBrowser
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 (piv[i]\text{piv}[i] is the row swapped with row ii at step ii). 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 U^\hat{\mat{U}} (i≤ji \le j) is obtained by subtracting from aija_{ij}, one by one, products l^iku^kj\hat l_{ik}\hat u_{kj} with k<ik < i: exactly the substitution calculation with l^ii=1\hat l_{ii} = 1 and no division. The previous proof’s argument gives u^ij=aij−∑k<il^iku^kj(1+θijk)\hat u_{ij} = a_{ij} - \sum_{k<i}\hat l_{ik}\hat u_{kj}(1 + \theta_{ijk}) except for factor (1+θ)(1 + \theta) on u^ij\hat u_{ij}, with ∣θ∣≤γi\abs{\theta} \le \gamma_i; rearranging,

∣aij−∑k=1il^ik u^kj∣≤γi∑k=1i∣l^ik∣ ∣u^kj∣.\Big|a_{ij} - \sum_{k=1}^{i}\hat l_{ik}\,\hat u_{kj}\Big| \le \gamma_i\sum_{k=1}^{i}\abs{\hat l_{ik}}\,\abs{\hat u_{kj}}.

For i>ji > j, multiplier l^ij\hat l_{ij} comes from taking aija_{ij}, subtracting products l^iku^kj\hat l_{ik}\hat u_{kj} with k<jk < j and dividing by u^jj\hat u_{jj}; the same calculation gives the inequality with sum through jj and γj\gamma_j. Since γi,γj≤γn\gamma_i, \gamma_j \le \gamma_n and the left sum is entry (i,j)(i, j) of L^U^\hat{\mat{L}}\hat{\mat{U}}, ∣A−L^U^∣≤γn∣L^∣∣U^∣\abs{\mat{A} - \hat{\mat{L}}\hat{\mat{U}}} \le \gamma_n\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}} follows. Rank-one-update elimination performs exactly these subtractions in this order, so the bound applies.

Solution. By the substitution theorem, (L^+ΔL)y^=b(\hat{\mat{L}} + \Delta\mat{L})\hat{\vb{y}} = \vb{b} and (U^+ΔU)x^=y^(\hat{\mat{U}} + \Delta\mat{U})\hat{\vb{x}} = \hat{\vb{y}} with ∣ΔL∣≤γn∣L^∣\abs{\Delta\mat{L}} \le \gamma_n\abs{\hat{\mat{L}}} and ∣ΔU∣≤γn∣U^∣\abs{\Delta\mat{U}} \le \gamma_n\abs{\hat{\mat{U}}}. Multiplying gives b=(L^+ΔL)(U^+ΔU)x^=(A+ΔA′)x^\vb{b} = (\hat{\mat{L}} + \Delta\mat{L})(\hat{\mat{U}} + \Delta\mat{U})\hat{\vb{x}} = (\mat{A} + \Delta\mat{A}')\hat{\vb{x}} with

ΔA′=ΔA+L^ ΔU+ΔL U^+ΔL ΔU,∣ΔA′∣≤(3γn+γn2) ∣L^∣∣U^∣≤γ3n∣L^∣∣U^∣,\Delta\mat{A}' = \Delta\mat{A} + \hat{\mat{L}}\,\Delta\mat{U} + \Delta\mat{L}\,\hat{\mat{U}} + \Delta\mat{L}\,\Delta\mat{U}, \qquad \abs{\Delta\mat{A}'} \le (3\gamma_n + \gamma_n^2)\,\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}} \le \gamma_{3n}\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}},

where the last inequality is 3γn+γn2≤γ3n3\gamma_n + \gamma_n^2 \le \gamma_{3n}, following from γj+γk+γjγk≤γj+k\gamma_j + \gamma_k + \gamma_j\gamma_k \le \gamma_{j+k} applied twice.

∎

Read this Gaussian elimination error analysis as follows: elimination is backward stable if and only if ∣L^∣∣U^∣\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}} is not much greater than ∣A∣\abs{\mat{A}}. It is never smaller (because ∣A∣≈∣L^U^∣≤∣L^∣∣U^∣\abs{\mat{A}} \approx \abs{\hat{\mat{L}}\hat{\mat{U}}} \le \abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}}), but may be enormously larger: product L^U^\hat{\mat{L}}\hat{\mat{U}} can reconstruct A\mat{A} of size 1 from mutually cancelling factors of size 101610^{16}, and the theorem guarantees error of order uu times factor size, not A\mat{A} size. Pivoting is about preventing factor growth.

Partial pivoting and growth factor

The tiny pivot

The smallest possible example shows everything. Let

A=[ε111],b=[12],x=11−ε[11−2ε]≈[11].\mat{A} = \begin{bmatrix} \varepsilon & 1 \\ 1 & 1 \end{bmatrix}, \qquad \vb{b} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}, \qquad \vb{x} = \frac{1}{1 - \varepsilon}\begin{bmatrix} 1 \\ 1 - 2\varepsilon \end{bmatrix} \approx \begin{bmatrix} 1 \\ 1 \end{bmatrix}.

The matrix is harmless: for small ε\varepsilon, κ∞(A)≈4\kappa_\infty(\mat{A}) \approx 4. Without pivoting, the multiplier is l21=1/εl_{21} = 1/\varepsilon and

L=[101/ε1],U=[ε101−1/ε].\mat{L} = \begin{bmatrix} 1 & 0 \\ 1/\varepsilon & 1 \end{bmatrix}, \qquad \mat{U} = \begin{bmatrix} \varepsilon & 1 \\ 0 & 1 - 1/\varepsilon \end{bmatrix}.

If ε<u\varepsilon < u, floating-point fl⁡(1−1/ε)=−1/ε\operatorname{fl}(1 - 1/\varepsilon) = -1/\varepsilon: the 1 at position (2,2)(2, 2) disappears, absorbed by a number 102010^{20} times larger. Computed factors are exact for matrix L^U^=[ε110]\hat{\mat{L}}\hat{\mat{U}} = \left[\begin{smallmatrix} \varepsilon & 1 \\ 1 & 0 \end{smallmatrix}\right], unlike A\mat{A}: ∣ΔA∣=1\abs{\Delta\mat{A}} = 1 at entry (2,2)(2, 2), and ∣L^∣∣U^∣\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}} has 2/ε2/\varepsilon there, so the theorem’s bound holds comfortably without saying anything useful. Solving gives x^2=fl⁡((2−1/ε)/(1−1/ε))=1\hat x_2 = \operatorname{fl}\big((2 - 1/\varepsilon)/(1 - 1/\varepsilon)\big) = 1 and x^1=(1−x^2)/ε=0\hat x_1 = (1 - \hat x_2)/\varepsilon = 0: 100% error in a problem with κ≈4\kappa \approx 4. Swapping rows first gives pivot 1, multiplier ε\varepsilon, and a good result.

[ ]The tiny pivot, with and without a swapBrowser
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 ε=10−4\varepsilon = 10^{-4} unpivoted error is order u/ε≈10−12u/\varepsilon \approx 10^{-12}; with 10−1010^{-10}, 10−710^{-7}; with 10−2010^{-20}, total. Error grows like u/εu/\varepsilon, exactly uu times factor size. The interactive does the same with matrix 5×55\times 5 with condition number κ2≈3.8\kappa_2 \approx 3.8, showing the in-place matrix at each step.

InteractiveGaussian elimination step by step
Back substitution with U^\hat{\mat{U}} and the transformed right-hand side.
col 1col 2col 3col 4col 5b
f11.0e−1312−113
f22.0e13−2.0e13−4.0e132.0e13−2.0e13−6.0e13
f31.0e130.5−420−2
f4−1.0e13−0.5−0.254.504.5
f51.0e130.5−1.50.2266
x̂0.9992011.0000001.0000001.0000001.000000
  • multipliers lijl_{ij} (stored where zeros were)
  • completed rows of U^\hat{\mat{U}}
  • entries grown beyond 103max⁡∣aij∣10^3\max\abs{a_{ij}}
back substitution
1.0 × 10⁻¹³
Arithmetic
Largest multiplier max⁡∣lij∣\max\abs{l_{ij}}2.0 × 10¹³
Growth factor ρ\rho1.3 × 10¹³
Information lost max⁡∣L^U^−PA∣\max\abs{\hat{\mat{L}}\hat{\mat{U}} - \mat{P}\mat{A}}8.0 × 10⁻⁴
Error in x^\hat{\vb{x}}: max⁡i∣x^i−1∣\max_i\abs{\hat x_i - 1}8.0 × 10⁻⁴
Same error with pivoting8.9 × 10⁻¹⁶
Only about 3 correct digits remain, and the problem is not to blame: with pivoting the error is 9 × 10⁻¹⁶.
The in-place matrix after each eliminated column: L\mat{L} multipliers in orange, completed U^\hat{\mat{U}} rows in blue, and active Schur complement uncolored; labels f1 to f5 identify the original row in each position. The right-hand side is b=A (1,…,1)⊤\vb{b} = \mat{A}\,(1, \dots, 1)\T computed in double, so the data solution is (1,…,1)(1, \dots, 1) up to relative error of order κu\kappa u. Elimination really runs in your browser, in double or exact float32 (each operation rounded with Math.fround). Start at the end: without pivoting and with ε=10−13\varepsilon = 10^{-13}, multipliers are order 101310^{13}, as is entry (2,2)(2, 2) of U^\hat{\mat{U}}, and the solution has lost about 13 digits. Step back to see where information is lost and enable pivoting.

The “information lost” readout, max⁡∣L^U^−PA∣\max\abs{\hat{\mat{L}}\hat{\mat{U}} - \mat{P}\mat{A}}, is the theorem’s ΔA\Delta\mat{A} actually measured: without pivoting it grows like u/εu/\varepsilon until, with ε≈10−16\varepsilon \approx 10^{-16}, it is as large as entries of A\mat{A} 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: ε≈10−7\varepsilon \approx 10^{-7} suffices to lose everything.

Growth factor

The strategy of partial pivoting and growth factor is as simple as possible: at step kk choose as pivot the largest-magnitude entry in column kk among rows k,…,nk, \dots, n and move its row up. This guarantees ∣lik∣≤1\abs{l_{ik}} \le 1: factor L^\hat{\mat{L}} is controlled. The size of U^\hat{\mat{U}} is measured by the

With partial pivoting, ∣l^ij∣≤1\abs{\hat l_{ij}} \le 1 and ∣u^ij∣≤ρnmax⁡∣aij∣\abs{\hat u_{ij}} \le \rho_n\max\abs{a_{ij}}, so (∣L^∣∣U^∣)ij≤n ρnmax⁡∣aij∣(\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}})_{ij} \le n\,\rho_n\max\abs{a_{ij}}, and summing rows Wilkinson’s theorem gives

∥ΔA′∥∞≤n2 γ3n ρn ∥A∥∞.\norm{\Delta\mat{A}'}_\infty \le n^2\,\gamma_{3n}\,\rho_n\,\norm{\mat{A}}_\infty.

Constant n2n^2 is pessimistic (Higham refines it in chapter 9, and observed backward error is typically order uu times a small constant); what matters is partial-pivoting elimination is backward stable exactly when ρn\rho_n is small. Is it always? Each step performs aij(k+1)=aij(k)−likakj(k)a^{(k+1)}_{ij} = a^{(k)}_{ij} - l_{ik}a^{(k)}_{kj} with ∣lik∣≤1\abs{l_{ik}} \le 1, so maximum entry magnitude can at most double per step:

ρn≤2n−1.\rho_n \le 2^{n-1}.

The bound is attained. The Wilkinson matrix has ones on the diagonal and last column, −1-1 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 −1-1, and each step adds the pivot row’s entry to the last column: that column becomes 1,2,4,…,2n−11, 2, 4, \dots, 2^{n-1}.

[ ]Wilkinson matrix: 2^(n-1) growth with κ ≈ nBrowser
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 (κ2≈27\kappa_2 \approx 27 with n=60n = 60), yet partial-pivoting elimination, as in scipy.linalg.solve, loses digits at the rate of 2n−12^{n-1}: with n=40n = 40 the solution has error 2.6×10−62.6\times 10^{-6} (about ten digits lost), and with n=60n = 60 error is 17% and backward error 6×10−36\times 10^{-3} is over 101310^{13} times uu. With n=60n = 60, ρ=259≈5.8×1017\rho = 2^{59} \approx 5.8\times 10^{17} exceeds 1/u1/u: the theorem promises nothing. Partial-pivoting elimination is not backward stable in the previous lesson’s strict sense: its backward-error constant depends on ρn\rho_n, 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.

InteractiveThe growth factor
Full logarithmic scale: each point is a random matrix
110⁴10⁸10¹²10¹⁶1/uWilkinson
Zoom: histogram of ρ\rho for n=32n = 32 (linear scale)
1.01.31.51.82.0calculating…
Observed median and maximum versus nn, and the 2n−12^{n-1} bound
11010²n=4n=8n=16n=32n=64n=1282ⁿ⁻¹
  • random matrices (median)
  • observed maximum
  • Wilkinson matrix, ρ=2n−1\rho = 2^{n-1}
32
Entries
Matrices calculated0 of 1000
Median ρ\rho…
Observed maximum…
Wilkinson: ρ=2n−1\rho = 2^{n-1}2.15 × 10⁹
Digits at stake: typical versus worst-case log⁡10ρ\log_{10}\rho…
Growth factor ρ\rho of partial-pivoting elimination for random n×nn\times n matrices generated and factored in your browser (fixed seed; computation proceeds in batches and the counter shows progress). Above on a full log scale: random-matrix cloud, Wilkinson-matrix diamond (2n−12^{n-1}, computed with the same code) and float64 line 1/u=2531/u = 2^{53}. Center: the same cloud enlarged on a linear scale; right: observed median and maximum versus nn on a log scale. Choose n=128n = 128: theoretical worst case is 37 orders of magnitude beyond what you see. Change the entry distribution: does anything change?

For Gaussian matrices median ρ\rho rises only from 1.3 with n=8n = 8 to 6 with n=128n = 128, and the maximum of 200 samples at n=128n = 128 is 10; worst case is 2127≈1.7×10382^{127} \approx 1.7\times 10^{38}. With signs ±1\pm 1 values are higher (median 25 at n=128n = 128), but still far from worst case. The distribution difference is mainly normalization: ρ\rho divides by the largest entry of A\mat{A}, which with signs ±1\pm 1 is 1 and with unit-variance Gaussians much larger (around 4 for n=128n = 128). The next cell measures this in Python with two literature normalizations:

[ ]Typical versus worst-case growthBrowser
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 A\mat{A}, as in the definition; the third by entry standard deviation (σ=1\sigma = 1), as Trefethen and Schreiber used in Average-case stability of Gaussian elimination (1990). They found that across distributions and n≤1024n \le 1024, mean growth is within a few percentage points of n2/3n^{2/3}; the cell’s median with far fewer samples fits as well. The difference between first and third columns is only the largest of n2n^2 Gaussians, growing roughly like 2ln⁡n2\sqrt{2\ln n^2} (about 4.4 for n=128n = 128). 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 nn 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 10−1210^{-12} breaks ties and growth falls from 2592^{59} to 2.

Costlier strategies offer stronger guarantees. Complete pivoting searches the entire active submatrix for its largest entry (swapping rows and columns), adding O(n3)\bigO(n^3) comparisons; Wilkinson proved growth bounded by a function slower than any exponential, of order n1/2 n14ln⁡nn^{1/2}\,n^{\frac14\ln n}. 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 A\mat{A} is symmetric positive definite, A=LL⊤\mat{A} = \mat{L}\mat{L}\T with lower-triangular L\mat{L} having positive diagonal. Equating column jj on both sides gives the column-by-column algorithm:

ljj=ajj−∑k<jljk2,lij=1ljj(aij−∑k<jlik ljk),i>j.l_{jj} = \sqrt{a_{jj} - \sum_{k<j} l_{jk}^2}, \qquad l_{ij} = \frac{1}{l_{jj}}\Big(a_{ij} - \sum_{k<j} l_{ik}\,l_{jk}\Big), \quad i > j.

By symmetry only half the products are computed and stored, costing 13n3\frac{1}{3}n^3 flops (plus nn square roots): half of LU. The radicand of ljjl_{jj} is the Gaussian-elimination pivot, entry (j,j)(j, j) of the Schur complement, positive exactly when the matrix is positive definite: in exact arithmetic Cholesky finishes if and only if A\mat{A} is positive definite.

Why it needs no pivoting

The diagonal equation says more. Since aii=∑k≤ilik2a_{ii} = \sum_{k \le i} l_{ik}^2 is a sum of squares,

∣lij∣≤aiipara todo j≤i.\abs{l_{ij}} \le \sqrt{a_{ii}} \qquad\text{para todo } j \le i.

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, L^L^⊤=A+ΔA\hat{\mat{L}}\hat{\mat{L}}\T = \mat{A} + \Delta\mat{A} with ∣ΔA∣≤γn+1∣L^∣∣L^⊤∣\abs{\Delta\mat{A}} \le \gamma_{n+1}\abs{\hat{\mat{L}}}\abs{\hat{\mat{L}}\T}. The dangerous term is bounded by Cauchy-Schwarz:

(∣L∣∣L⊤∣)ij=∑k∣lik∣ ∣ljk∣≤(∑klik2)1/2(∑kljk2)1/2=aii ajj.\big(\abs{\mat{L}}\abs{\mat{L}\T}\big)_{ij} = \sum_k \abs{l_{ik}}\,\abs{l_{jk}} \le \Big(\sum_k l_{ik}^2\Big)^{1/2}\Big(\sum_k l_{jk}^2\Big)^{1/2} = \sqrt{a_{ii}\,a_{jj}}.

Thus ∣Δaij∣≲γn+1aiiajj\abs{\Delta a_{ij}} \lesssim \gamma_{n+1}\sqrt{a_{ii}a_{jj}} (for computed factors, up to terms of order u2u^2): backward error is bounded by the matrix itself, without a growth factor. In 2-norm, ∥ΔA∥2≤γn+1∥∣L∣∥22≤γn+1 n ∥A∥2\norm{\Delta\mat{A}}_2 \le \gamma_{n+1}\norm{\abs{\mat{L}}}_2^2 \le \gamma_{n+1}\,n\,\norm{\mat{A}}_2, because ∥∣L∣∥2≤∥L∥F≤n ∥L∥2\norm{\abs{\mat{L}}}_2 \le \norm{\mat{L}}_F \le \sqrt{n}\,\norm{\mat{L}}_2. 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.

InteractiveCholesky transforms a circle into an ellipse
  • unit circle
  • {y:y⊤A−1y=1}=L⋅\{\vb{y} : \vb{y}\T\mat{A}^{-1}\vb{y} = 1\} = \mat{L}\cdot circle
  • columns of L\mat{L}
Starting point
1.50
1.00
1.00
0.00
l11=1.500=1.225l21=a21/l11=0.816a22−l212=0.333l22=0.333=0.577\begin{aligned} &l_{11} = \sqrt{1.500} = 1.225 \\ &l_{21} = a_{21}/l_{11} = 0.816 \\ &a_{22} - l_{21}^2 = 0.333 \\ &l_{22} = \sqrt{0.333} = 0.577 \end{aligned}
Eigenvalues of A+δI\mat{A} + \delta\mat{I}2.281, 0.219
∣l21∣≤a22\abs{l_{21}} \le \sqrt{a_{22}}0.816 ≤ 1.000
κ2(A+δI)\kappa_2(\mat{A} + \delta\mat{I})10.40
Cholesky completes: the matrix is positive definite and L\mat{L} maps the circle to the ellipse.
Symmetric 2×22\times 2 matrix with entries a11a_{11}, a12=a21a_{12} = a_{21}, a22a_{22} and added diagonal δ\delta. If A+δI\mat{A} + \delta\mat{I} is positive definite, factor L\mat{L} maps the unit circle (gray) to magenta ellipse {y:y⊤A−1y=1}\{\vb{y} : \vb{y}\T\mat{A}^{-1}\vb{y} = 1\}, the one-standard-deviation ellipse of N(0,A)\mathcal{N}(\vb{0}, \mat{A}); arrows are columns of L\mat{L}, images of e1\vb{e}_1 and e2\vb{e}_2. Right: the algorithm's three numerical steps. Raise a12a_{12} from the initial state: the ellipse flattens, l22l_{22} approaches 0 and, when a122>a11a22a_{12}^2 > a_{11}a_{22}, step 2's radicand becomes negative and the conic becomes a hyperbola. Then try “almost semidefinite” and increase jitter.

The interactive shows factorization geometry: L\mat{L} is a square root of A\mat{A} deforming the unit sphere into the ellipsoid of A\mat{A}, making it the tool for sampling multivariate normals (x=Lz\vb{x} = \mat{L}\vb{z} with z∼N(0,I)\vb{z} \sim \mathcal{N}(\vb{0}, \mat{I})). It also shows failure: the algorithm does not “know” the matrix is not positive definite until finding a negative radicand, exactly when Schur complement a22−a212/a11a_{22} - a_{21}^2/a_{11} ceases to be positive, i.e. when det⁡A=a11(a22−a212/a11)≤0\det\mat{A} = a_{11}(a_{22} - a_{21}^2/a_{11}) \le 0.

Failure as a numerical test and jitter

This makes Cholesky the cheapest way to check whether a symmetric matrix is positive definite: attempt factorization (13n3\frac13 n^3 flops versus several n3n^3 for eigenvalues). In floating point the question changes. Backward error is order numax⁡iaiinu\max_i a_{ii}, so the algorithm works with a matrix indistinguishable from A+ΔA\mat{A} + \Delta\mat{A}; if λmin⁡(A)\lambda_{\min}(\mat{A}) 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: λmin⁡\lambda_{\min} of the unit-diagonal-rescaled matrix greater than an amount of order nγn+1n\gamma_{n+1}.) This happened in the motivation: Gaussian-kernel eigenvalues decay exponentially, hundreds fall below 200u≈2×10−14200u \approx 2\times 10^{-14}, and the matrix is singular in float64.

The usual solution is jitter: factor A+δI\mat{A} + \delta\mat{I} with small δ>0\delta > 0. It raises every eigenvalue by δ\delta and brings condition number to (λmax⁡+δ)/(λmin⁡+δ)≤(λmax⁡+δ)/δ(\lambda_{\max} + \delta)/(\lambda_{\min} + \delta) \le (\lambda_{\max} + \delta)/\delta. But it changes the problem: you solve another system and compute another matrix’s log determinant, ∑ilog⁡(λi+δ)\sum_i\log(\lambda_i + \delta), potentially very different when many λi\lambda_i are below δ\delta. In a Gaussian process δ\delta 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.

[ ]Cholesky from scratch, failure and jitterBrowser
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 ∣lij∣≤aii\abs{l_{ij}} \le \sqrt{a_{ii}} holds (maximum ratio exactly 1, at l11=a11l_{11} = \sqrt{a_{11}}). With the Gaussian kernel, the radicand becomes negative already at column 5. Minimum working jitter here is 10−1410^{-14}, rounding-noise level, but observe the last column: between δ=10−14\delta = 10^{-14} and δ=10−6\delta = 10^{-6} log determinant changes by about 3400 nats because 190 of 200 exact eigenvalues of K\mat{K} are below 10−610^{-6} and each contributes log⁡(λi+δ)≈log⁡δ\log(\lambda_i + \delta) \approx \log\delta. Jitter would dominate a maximized likelihood. With realistic observation noise σ2=10−4\sigma^2 = 10^{-4}, all eigenvalues exceed 10−410^{-4} (κ≈106\kappa \approx 10^6), factorization needs no jitter and the effect of δ\delta is first-order δ tr⁡((K+σ2I)−1)≲δn/σ2\delta\,\operatorname{tr}\big((\mat{K} + \sigma^2\mat{I})\inv\big) \lesssim \delta n/\sigma^2: adding 10−1010^{-10} changes the fourth decimal of log determinant and 10−810^{-8} 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 −y′′=f-y'' = f on a grid of nn points with finite differences gives the tridiagonal matrix tridiag⁡(−1,2,−1)\operatorname{tridiag}(-1, 2, -1); cubic splines, smoothing filters and the implicit Crank–Nicolson scheme for the heat equation give tridiagonal or pentadiagonal matrices. A matrix has lower bandwidth pp and upper bandwidth qq if aij=0a_{ij} = 0 when i>j+pi > j + p or j>i+qj > i + q.

The key observation is that elimination without pivoting creates no entries outside the band: step kk only touches rows k+1,…,k+pk + 1, \dots, k + p (the only ones with aik≠0a_{ik} \neq 0) and columns k+1,…,k+qk + 1, \dots, k + q within them. Thus L\mat{L} has lower bandwidth pp and U\mat{U} upper bandwidth qq, and the cost is O(npq)\bigO(npq) instead of O(n3)\bigO(n^3): about 2npq2npq flops. With partial pivoting, swaps can bring up rows with pp more entries, and the upper bandwidth of U\mat{U} becomes p+qp + q; the cost remains linear in nn.

For a tridiagonal matrix (p=q=1p = q = 1) with subdiagonal aia_i, diagonal bib_i and superdiagonal cic_i, elimination without pivoting is the Thomas algorithm:

c1′=c1b1,d1′=d1b1,ci′=cibi−aici−1′,di′=di−aidi−1′bi−aici−1′,xn=dn′,xi=di′−ci′ xi+1.c'_1 = \frac{c_1}{b_1},\quad d'_1 = \frac{d_1}{b_1},\qquad c'_i = \frac{c_i}{b_i - a_i c'_{i-1}},\quad d'_i = \frac{d_i - a_i d'_{i-1}}{b_i - a_i c'_{i-1}},\qquad x_n = d'_n,\quad x_i = d'_i - c'_i\,x_{i+1}.

That takes about 8n8n flops: linear time. The denominator bi−aici−1′b_i - a_ic'_{i-1} is the pivot uiiu_{ii}, and the usual question is whether it can be tiny. It cannot in the two cases covering almost all applications: if A\mat{A} 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 ρn≤2\rho_n \le 2 (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.

[ ]The Thomas algorithm versus solve_bandedBrowser
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 3×10−123\times 10^{-12}, the κu\kappa u level for this matrix (κ2≈4(n+1)2/π2≈4×105\kappa_2 \approx 4(n+1)^2/\pi^2 \approx 4\times 10^5), and multiplying nn 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 3232 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 kk, every row with a nonzero in column kk receives a multiple of row kk, and every pair of neighbors of kk becomes connected. Zero entries of A\mat{A} that become nonzero in L\mat{L} are called fill-in. An arrow matrix, with the diagonal and a single dense row and column, is the extreme example:

InteractiveOrdering matters: fill-in in sparse matrices
Pattern of A\mat{A}
Pattern of L\mat{L} after 12 steps
  • nonzero in A\mat{A}
  • fill-in created through this step
  • column just eliminated
column 12 eliminated
Ordering
12
Nonzeros in lower triangle of A\mat{A}23
Nonzeros in L\mat{L}78
Fill-in (zeros in A\mat{A} filled by L\mat{L})55
Flops ≈∑kck2\approx \sum_k c_k^2506
Dense Cholesky, n3/3n^3/3576
Pattern of a symmetric positive definite matrix and its Cholesky factor L\mat{L} obtained by symbolic factorization (assuming no exact cancellations). Step kk connects all rows with a nonzero in column kk; red marks zero entries of A\mat{A} made nonzero by the step. Initially the arrow has its dense row first and is already factored: L\mat{L} is full. Go back to step 1 to see why, then switch to the dense row last. The flop count is ∑kck2\sum_k c_k^2, where ckc_k is the number of nonzeros below the diagonal in column kk of L\mat{L}.

With the dense row first, the first step connects all variables and L\mat{L} becomes completely full: n(n+1)/2n(n+1)/2 nonzeros and O(n3)\bigO(n^3) flops. With the same matrix and unknowns in another order (the dense variable last), there is no fill-in: 2n−12n - 1 nonzeros and O(n)\bigO(n) flops. Symmetrically reordering rows and columns, PAP⊤\mat{P}\mat{A}\mat{P}\T, 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 x=A−1b\vb{x} = \mat{A}\inv\vb{b} on paper is correct; writing np.linalg.inv(A) @ b in a program almost never is. There are two reasons.

Cost. Forming A−1\mat{A}\inv costs about 2n32n^3 flops with LAPACK’s dedicated routine (getri, which exploits the factors’ structure) and 83n3\frac83 n^3 if AX=I\mat{A}\mat{X} = \mat{I} is solved by brute force, as np.linalg.inv does. Solving one system costs 23n3\frac23 n^3. For one right-hand side, the inverse costs three to four times as many flops and gains nothing: multiplying by A−1\mat{A}\inv costs 2n22n^2, the same as solving with the computed factors.

Accuracy. You saw this in the previous lesson’s stability map: fl⁡(X^b)\operatorname{fl}(\hat{\mat{X}}\vb{b}) with X^≈A−1\hat{\mat{X}} \approx \mat{A}\inv has forward error similar to elimination, but its residual is of order κ(A) u∥A∥∥x^∥\kappa(\mat{A})\,u\norm{\mat{A}}\norm{\hat{\vb{x}}}: it is not backward stable.

The same applies to the determinant. det⁡A\det\mat{A} follows from LU at no extra cost, det⁡A=det⁡(P)−1∏iuii=±∏iuii\det\mat{A} = \det(\mat{P})^{-1}\prod_i u_{ii} = \pm\prod_i u_{ii}, with the permutation’s sign (the parity of the number of swaps); with Cholesky, det⁡A=∏ilii2\det\mat{A} = \prod_i l_{ii}^2. But the product of nn numbers readily overflows or underflows: the determinant of 0.1 I4000.1\,\mat{I}_{400} is 10−40010^{-400}, which cannot be represented in float64. What is almost always needed is the log-determinant:

log⁡∣det⁡A∣=∑i=1nlog⁡∣uii∣,log⁡det⁡A=2∑i=1nlog⁡lii (Cholesky).\log\abs{\det\mat{A}} = \sum_{i=1}^n \log\abs{u_{ii}}, \qquad \log\det\mat{A} = 2\sum_{i=1}^n\log l_{ii}\ \text{(Cholesky)}.

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 L^U^\hat{\mat{L}}\hat{\mat{U}} and a solution x^0\hat{\vb{x}}_0. Its residual r0=b−Ax^0\vb{r}_0 = \vb{b} - \mat{A}\hat{\vb{x}}_0 satisfies A(x−x^0)=r0\mat{A}(\vb{x} - \hat{\vb{x}}_0) = \vb{r}_0: the error is the solution of another system with the same matrix. Solving it using the factors you already have (2n22n^2 flops) and adding the correction gives iterative refinement:

rk=b−Ax^k,L^U^ dk=Prk,x^k+1=x^k+dk.\vb{r}_k = \vb{b} - \mat{A}\hat{\vb{x}}_k, \qquad \hat{\mat{L}}\hat{\mat{U}}\,\vb{d}_k = \mat{P}\vb{r}_k, \qquad \hat{\vb{x}}_{k+1} = \hat{\vb{x}}_k + \vb{d}_k.

Why does it not always give the exact solution in one step? Because the factors belong to A+ΔA\mat{A} + \Delta\mat{A}, not A\mat{A}. If the operations in the step were exact, dk=(A+ΔA)−1A(x−x^k)\vb{d}_k = (\mat{A} + \Delta\mat{A})\inv\mat{A}(\vb{x} - \hat{\vb{x}}_k), and therefore

x−x^k+1=(I−(A+ΔA)−1A)(x−x^k)=(A+ΔA)−1ΔA (x−x^k).\vb{x} - \hat{\vb{x}}_{k+1} = \big(\mat{I} - (\mat{A} + \Delta\mat{A})\inv\mat{A}\big)(\vb{x} - \hat{\vb{x}}_k) = (\mat{A} + \Delta\mat{A})\inv\Delta\mat{A}\,(\vb{x} - \hat{\vb{x}}_k).

At each step the error is multiplied by a matrix with norm

∥(A+ΔA)−1ΔA∥≤∥A−1∥∥ΔA∥1−∥A−1∥∥ΔA∥≈κ(A) ∥ΔA∥∥A∥≈cn ρn κ(A) uf,\norm{(\mat{A} + \Delta\mat{A})\inv\Delta\mat{A}} \le \frac{\norm{\mat{A}\inv}\norm{\Delta\mat{A}}}{1 - \norm{\mat{A}\inv}\norm{\Delta\mat{A}}} \approx \kappa(\mat{A})\,\frac{\norm{\Delta\mat{A}}}{\norm{\mat{A}}} \approx c_n\,\rho_n\,\kappa(\mat{A})\,u_f,

where ufu_f is the unit roundoff of the precision used for factorization. Refinement converges linearly, with a rate bounded by something of order κuf\kappa u_f, if κ(A) uf\kappa(\mat{A})\,u_f 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 uru_r, and the error in the sum x^k+dk\hat{\vb{x}}_k + \vb{d}_k, with unit uu. Roughly (Higham, chapter 12), the final error is of order u+κ(A) uru + \kappa(\mat{A})\,u_r. This gives three uses of iterative refinement:

  • Classical (Wilkinson, Moler 1967): factor in working precision and compute the residual in double precision, ur=u2u_r = u^2. The final error falls to ≈u\approx u, independent of κ\kappa, provided κu<1\kappa u < 1.
  • Fixed precision (ur=uu_r = u): it does not improve forward error beyond κu\kappa u, 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 uf=2−24u_f = 2^{-24} it converges if κ≪1/uf≈1.7×107\kappa \ll 1/u_f \approx 1.7\times 10^7, and the result has the accuracy of float64 elimination (≈κu64\approx\kappa u_{64}) for the price of a float32 factorization. Langou and coauthors popularized it in 2006, and it is LAPACK’s dsgesv routine. With GPU tensor units, which factor in float16 or bfloat16 at much higher speeds, it underpins mixed-precision refinement in the frontier lesson.
InteractiveMixed-precision iterative refinement
Relative error ∥xk−x∥∞/∥x∥∞\norm{\vb{x}_k - \vb{x}}_\infty/\norm{\vb{x}}_\infty at each iteration (n=40n = 40)
10⁻¹⁶10⁻¹²10⁻⁸10⁻⁴110⁴012345678910u₆₄κ·u₃₂κ·u₆₄calculating…iteration k
  • LU in float32, residual and update in float64 (mixed)
  • all in float32
  • u64u_{64} and κu64\kappa u_{64}
1.0 × 10⁴
Predicted contraction ≈κ u32\approx \kappa\, u_{32}6.0 × 10⁻⁴
Observed contraction (average per iteration)…
Error after 10 iterations (mixed)…
Pivoted elimination in float64…
Iterations to float64 level…
A 40×4040\times 40 matrix with prescribed κ2(A)\kappa_2(\mat{A}) (Udiag⁡(s)V⊤\mat{U}\operatorname{diag}(\vb{s})\mat{V}\T with logarithmically spaced singular values), factored with partial pivoting in exact float32 in your browser. Blue: the dsgesv mixed scheme, with residual and update in float64 and correction in float32. Orange: everything in float32. Error is measured against the exact solution of the stored data (double-precision elimination refined with double-double residuals). Dashed lines: κu32\kappa u_{32} (factorization alone), κu64\kappa u_{64} (float64 elimination), and u64u_{64}. With κ=104\kappa = 10^4, each iteration gains about 4 digits and two reach the float64 level. Increase κ\kappa to 10910^9 and compare observed and predicted contraction.

The interactive shows both theoretical predictions and a nuance. The blue curve stops at κu64\kappa u_{64}, the level of float64 elimination, as the bound u+κuru + \kappa u_r with ur=u64u_r = u_{64} says; the orange curve, without extra residual precision, stays at κu32\kappa u_{32} from the first iteration: refinement in the same precision does not improve forward error. Observed contraction grows in proportion to κu32\kappa u_{32}, but is 15 to 30 times smaller: 4×10−54\times 10^{-5} per step with κ=104\kappa = 10^4, 3×10−33\times 10^{-3} with 10610^6, 0.030.03 with 10710^7 and 0.440.44 with 10810^8, where κu32≈6\kappa u_{32} \approx 6 and iteration still converges, slowly. With 10910^9 it diverges. The bound ∥A−1∥∥ΔA∥\norm{\mat{A}\inv}\norm{\Delta\mat{A}} assumes ΔA\Delta\mat{A} points in the worst possible direction, which factorization roundoff does not; the threshold’s order of magnitude, κ≈1/uf\kappa \approx 1/u_f, 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 n3n^3 and that inversion is more expensive and less reliable than solving.

[ ]Measuring cubic scalingBrowser
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 nn rises toward 8 as nn 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 nn 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.

[ ]solve versus inv(A) @ b: time and errorBrowser
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 κ=1010\kappa = 10^{10}, both solutions have forward errors of order κu≈10−6\kappa u \approx 10^{-6} or less (larger for the inverse), but the inverse has backward error hundreds of millions of times larger than uu (it grows with κ\kappa, 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 A−1\mat{A}\inv 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.

[ ]Float32 LU, float64 residualsBrowser
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 κ=102\kappa = 10^2, two iterations suffice to reach float64 level. With 10410^4 and 10610^6 more steps are needed, each dividing the error by a factor following 1/(κu32)1/(\kappa u_{32}) with a favorable constant: about 10410^4 times with κ=104\kappa = 10^4 (κu32≈6×10−4\kappa u_{32} \approx 6\times 10^{-4}), and about 100 with κ=106\kappa = 10^6 (κu32≈0.06\kappa u_{32} \approx 0.06). Finally the solution has the same error as solve in float64. With 10710^7, κu32≈0.6\kappa u_{32} \approx 0.6 is no longer small, but for these matrices actual contraction is 0.05 to 0.1 per step and iteration still converges slowly; with 10810^8 (κu32≈6\kappa u_{32} \approx 6) 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 x\vb{x} used to construct b\vb{b}, so it includes rounding error in b\vb{b}, of order κu64\kappa u_{64}: that is the floor for refinement and solve.

Next, the log-determinant. The log-likelihood of y∼N(0,Σ)\vb{y} \sim \mathcal{N}(\vb{0}, \mat{\Sigma}) is

log⁡p(y)=−12 y⊤Σ−1y−12log⁡det⁡Σ−n2log⁡2π,\log p(\vb{y}) = -\tfrac12\,\vb{y}\T\mat{\Sigma}\inv\vb{y} - \tfrac12\log\det\mat{\Sigma} - \tfrac{n}{2}\log 2\pi,

and with Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T the two difficult terms come from the same factorization: y⊤Σ−1y=∥L−1y∥22\vb{y}\T\mat{\Sigma}\inv\vb{y} = \norm{\mat{L}\inv\vb{y}}_2^2 (forward substitution) and log⁡det⁡Σ=2∑ilog⁡lii\log\det\mat{\Sigma} = 2\sum_i\log l_{ii}. This is how a Gaussian process evaluates its log-likelihood.

[ ]Gaussian log-likelihood without overflowBrowser
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 e−1748≈10−759e^{-1748} \approx 10^{-759}) and, scaling the matrix by 10310^3, overflows to infinity; the Cholesky log-determinant is a well-behaved four-digit number and agrees with slogdet. The log-likelihood never uses Σ−1\mat{\Sigma}\inv or det⁡Σ\det\mat{\Sigma}.

In libraries

SituationSciPyWhat it calls
One general systemscipy.linalg.solve(A, b) or np.linalg.solvegesv: LU with partial pivoting and substitutions
Many right-hand sides arriving separatelylu, piv = lu_factor(A) then lu_solve((lu, piv), b)getrf once, getrs (2n22n^2) each time
Symmetric positive definitec = cho_factor(A), cho_solve(c, b), or solve(A, b, assume_a="pos")potrf and potrs: Cholesky, half the flops
Bandedsolve_banded((p, q), ab, b); if also positive definite, solveh_bandedgbsv, pbsv, gtsv
Explicit factorsP, L, U = scipy.linalg.lu(A) (convention A=PLU\mat{A} = \mat{P}\mat{L}\mat{U})getrf and reconstruction
Direct accessscipy.linalg.lapack.dgetrf, dpotrfLAPACK 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 A=PLU\mat{A} = \mat{P}\mat{L}\mat{U}, opposite to PA=LU\mat{P}\mat{A} = \mat{L}\mat{U} in textbooks: to solve, apply P⊤\mat{P}\T to the right-hand side. And lu_factor returns LAPACK swaps, not the permutation.

[ ]Factor once, solve many timesBrowser
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

NumericThe price of LU
Approximately how many flops does LU factorization of a dense 1000×10001000\times 1000 matrix cost? Give the number of flops (floating-point additions, subtractions, multiplications and divisions).
NumericWorst-case partial pivoting
What is the growth factor ρ30\rho_{30} of elimination with partial pivoting (breaking ties in favor of the first row) on the 30×3030\times 30 Wilkinson matrix?
NumericAn arrow pointing the wrong way
Let A∈R100×100\mat{A} \in \R^{100\times 100} be symmetric positive definite with an arrow pattern: a dense diagonal, first row and first column, with zeros elsewhere. Assuming no exact cancellations, how many nonzero entries does its Cholesky factor L\mat{L} have (including the diagonal)?
QuizFive hundred right-hand sides
You must solve Axi=bi\mat{A}\vb{x}_i = \vb{b}_i for 500 vectors bi\vb{b}_i arriving one by one, with dense, well-conditioned A\mat{A} of size 2000×20002000\times 2000. Which option is best in cost and accuracy?
QuizWhat does partial pivoting guarantee?
For float64 Gaussian elimination with partial pivoting, which statement is true for every invertible A∈Rn×n\mat{A} \in \R^{n\times n}?
QuizCholesky fails in a Gaussian process
You fit a Gaussian process with 3000 very close points and a Gaussian kernel, without a noise term. np.linalg.cholesky(K) raises LinAlgError. What do you do?
QuizWhen does refinement converge?
You factor A\mat{A} in float32 (u32≈6×10−8u_{32} \approx 6\times 10^{-8}) and refine with residual and update in float64. In which case do you expect float64 elimination accuracy in a few iterations?
QuizFactors from scipy.linalg.lu
With P, L, U = scipy.linalg.lu(A), using convention A=PLU\mat{A} = \mat{P}\mat{L}\mat{U}, how do you solve Ax=b\mat{A}\vb{x} = \vb{b}?
ProofCholesky needs no pivoting
Prove: Let A∈Rn×n\mat{A} \in \R^{n\times n} be symmetric positive definite with Cholesky factor L\mat{L} (A=LL⊤\mat{A} = \mat{L}\mat{L}\T, positive diagonal). Prove ∣lij∣≤aii\abs{l_{ij}} \le \sqrt{a_{ii}} for j≤ij \le i, that intermediate elimination matrices have no entries larger than max⁡i,j∣aij∣\max_{i,j}\abs{a_{ij}}, and that (∣L∣∣L⊤∣)ij≤aiiajj(\abs{\mat{L}}\abs{\mat{L}\T})_{ij} \le \sqrt{a_{ii}a_{jj}}.
0
Recall that a symmetric positive definite matrix has its largest absolute entry on the diagonal, because aij2<aiiajja_{ij}^2 < a_{ii}a_{jj} for i≠ji \neq j (the determinant of the corresponding positive definite 2×22\times 2 submatrix).

Step 1 of 4. What relation does entry (i,i)(i, i) of A=LL⊤\mat{A} = \mat{L}\mat{L}\T give?

CodeA positive definite solver with diagnostics
Implement solve_spd(A, b) to solve Ax=b\mat{A}\vb{x} = \vb{b} for symmetric positive definite A\mat{A} 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 A\mat{A} is not square, is not symmetric (relative tolerance 10−1210^{-12} on max⁡∣aij∣\max\abs{a_{ij}}), or a Cholesky radicand is ≤0\le 0 (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)
Shift+Enter to run
CodeSign and log-determinant from LU
Implement slogdet_lu(A) returning (sign, logabsdet) like np.linalg.slogdet: the determinant sign (+1+1, −1-1, or 00 if singular) and log⁡∣det⁡A∣\log\abs{\det\mat{A}} (−∞-\infty 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 (−1)nuˊmero de intercambios(-1)^{\text{número de intercambios}}, and the logarithm is the sum of log⁡∣uii∣\log\abs{u_{ii}}. 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.0
Shift+Enter to run

Summary

Key idea
Floating-point Gaussian elimination gives the exact factorization of a nearby matrix, L^U^=PA+ΔA\hat{\mat{L}}\hat{\mat{U}} = \mat{P}\mat{A} + \Delta\mat{A} with ∣ΔA∣≤γn∣L^∣∣U^∣\abs{\Delta\mat{A}} \le \gamma_n\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}}: it is backward stable as long as the factors do not grow. Partial pivoting bounds L\mat{L} and leaves the size of U\mat{U} to the growth factor, which can be 2n−12^{n-1} but is small in practice. Cholesky needs no pivoting because positive definiteness bounds its factors by the diagonal.
  • Triangular systems cost n2n^2 flops and substitution is entrywise backward stable, although triangular matrices may be very ill conditioned.
  • LU costs 23n3\frac23 n^3 flops, Cholesky 13n3\frac13 n^3 and solving with the factors 2n22n^2: factor once and reuse. The flop count predicts scaling (×8\times 8 when doubling nn), not absolute time.
  • Without pivoting, a pivot ε\varepsilon produces multipliers 1/ε1/\varepsilon that erase matrix information. With partial pivoting ∣lij∣≤1\abs{l_{ij}} \le 1 and ρn≤2n−1\rho_n \le 2^{n-1}; Wilkinson’s matrix reaches the bound, but for random matrices ρ\rho grows as a small power of nn.
  • Cholesky is backward stable without pivoting (∣lij∣≤aii\abs{l_{ij}} \le \sqrt{a_{ii}}); 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 O(npq)\bigO(npq) and tridiagonal ones in O(n)\bigO(n) using Thomas; in sparse matrices variable ordering determines fill.
  • Never form A−1\mat{A}\inv to solve: it costs more and is not backward stable. The log-determinant comes from the diagonal of U\mat{U} or L\mat{L} without overflow.
  • Iterative refinement converges at a rate proportional to κuf\kappa u_f (smaller in practice) and reaches error ≈u+κur\approx u + \kappa u_r: factor in float32 and refine in float64 for float64 accuracy if κ≪1/u32\kappa \ll 1/u_{32}.