AnyLearn
All lessons
Mathadvanced

Solving Ax = b Directly: LU, Pivoting, and Never Inverting

How a computer actually solves a linear system: Gaussian elimination as an LU factorisation, why you factor once and never invert, how a tiny pivot wrecks a harmless problem, what partial pivoting and the growth factor guarantee, when Cholesky applies, and where fill-in ends the direct approach.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

Elimination is a factorisation in disguise

Gaussian elimination, the row reduction taught in a first linear algebra course, subtracts multiples of each pivot row from the rows below it until the matrix is upper triangular. If you write down the multipliers instead of throwing them away, they form a unit lower triangular matrix LL, and the triangular result is UU:

A=LU⟹Ax=b   becomes   Ly=b,    Ux=yA = LU \quad\Longrightarrow\quad A\mathbf{x} = \mathbf{b} \;\text{ becomes }\; L\mathbf{y} = \mathbf{b},\;\; U\mathbf{x} = \mathbf{y}

Both triangular systems are solved by substitution, one unknown at a time. Seeing elimination as a factorisation changes how you use it: the expensive part depends only on AA, so it can be done once and reused for every right-hand side.

Key idea: a direct solver is a factorisation plus two cheap triangular solves. Choosing a solver means choosing the factorisation that fits the matrix.

This lesson assumes the idea of a condition number from Conditioning and Stability: Whose Fault Is the Error, and leaves least squares and QR in depth to SVD and Least Squares.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. Elimination is a factorisation in disguise

Gaussian elimination, the row reduction taught in a first linear algebra course, subtracts multiples of each pivot row from the rows below it until the matrix is upper triangular. If you write down the multipliers instead of throwing them away, they form a unit lower triangular matrix LL, and the triangular result is UU:

A=LU⟹Ax=b   becomes   Ly=b,    Ux=yA = LU \quad\Longrightarrow\quad A\mathbf{x} = \mathbf{b} \;\text{ becomes }\; L\mathbf{y} = \mathbf{b},\;\; U\mathbf{x} = \mathbf{y}

Both triangular systems are solved by substitution, one unknown at a time. Seeing elimination as a factorisation changes how you use it: the expensive part depends only on AA, so it can be done once and reused for every right-hand side.

Key idea: a direct solver is a factorisation plus two cheap triangular solves. Choosing a solver means choosing the factorisation that fits the matrix.

This lesson assumes the idea of a condition number from Conditioning and Stability: Whose Fault Is the Error, and leaves least squares and QR in depth to SVD and Least Squares.

2. What each factorisation costs

Operation counts for an n×nn \times n matrix, leading terms as derived in Trefethen and Bau's Numerical Linear Algebra (Lectures 10, 17, 20 and 23):

StepFlopsApplies to
LU (Gaussian elimination)23n3\tfrac{2}{3} n^3Any nonsingular matrix, with pivoting
Cholesky A=R⊤RA = R^\top R13n3\tfrac{1}{3} n^3Symmetric positive definite only
Householder QR43n3\tfrac{4}{3} n^3Any matrix, square or tall
One triangular solven2n^2After any of the above

The gap between n3n^3 and n2n^2 is the practical lesson. For n=104n = 10^4, the LU factorisation is about 6.7×10116.7 \times 10^{11} flops, while each additional right-hand side, a forward and a back substitution, is about 2×1082 \times 10^8: over three thousand times cheaper.

In practice: when the same matrix meets many right-hand sides, as in Newton iterations with a frozen Jacobian or implicit time stepping, factor with scipy.linalg.lu_factor once and call lu_solve per vector instead of calling solve each time.

3. Solve, do not invert

The formula x=A−1b\mathbf{x} = A^{-1}\mathbf{b} is notation, not an algorithm. Computing the inverse costs more arithmetic than one factorisation, and Higham's Accuracy and Stability of Numerical Algorithms shows that solving through it is not backward stable. Compare on the 10 by 10 Hilbert matrix:

import numpy as np
from scipy.linalg import hilbert, lu_factor, lu_solve

H = hilbert(10)                     # a famously ill-conditioned matrix
x_true = np.ones(10)
b = H @ x_true

def report(name, x):
    back = np.linalg.norm(b - H @ x) / (np.linalg.norm(H) * np.linalg.norm(x))
    fwd = np.linalg.norm(x - x_true) / np.linalg.norm(x_true)
    print(f"{name:9s} backward error {back:.1e}   forward error {fwd:.1e}")

report("solve", np.linalg.solve(H, b))
report("inv @ b", np.linalg.inv(H) @ b)
print(f"cond(H) = {np.linalg.cond(H):.1e}")

lu, piv = lu_factor(H)              # factor once
for k in range(3):                  # reuse for many right-hand sides
    bk = H @ np.full(10, k + 1.0)
    print("rhs", k, lu_solve((lu, piv), bk)[:3].round(4))
solve     backward error 1.0e-16   forward error 8.7e-05
inv @ b   backward error 8.5e-06   forward error 2.8e-03
cond(H) = 1.6e+13
rhs 0 [1. 1. 1.]
rhs 1 [2. 2. 2.]
rhs 2 [3. 3. 3.]

np.linalg.solve, which NumPy documents as calling LAPACK's gesv (LU with partial pivoting), returns an answer that exactly solves a system within rounding of the one given. The inverse route is about 101110^{11} times worse by that measure, and its answer is about 30 times less accurate.

4. A tiny pivot destroys a harmless problem

Elimination divides by the pivot akka_{kk}. A zero pivot is the obvious failure. A tiny one is worse, because nothing crashes.

Predict first

The matrix (10−20111)\begin{pmatrix} 10^{-20} & 1 \\ 1 & 1 \end{pmatrix} has condition number about 2.6, and the system with right-hand side (1,2)(1, 2) has solution very close to (1,1)(1, 1). What does elimination without row swaps return?

import numpy as np

def solve_no_pivot(A, b):
    A, b = A.astype(float).copy(), b.astype(float).copy()
    n = len(b)
    for k in range(n - 1):
        for i in range(k + 1, n):
            m = A[i, k] / A[k, k]          # multiplier
            A[i, k:] -= m * A[k, k:]
            b[i] -= m * b[k]
    x = np.zeros(n)
    for i in reversed(range(n)):
        x[i] = (b[i] - A[i, i+1:] @ x[i+1:]) / A[i, i]
    return x

A = np.array([[1e-20, 1.0],
              [1.0,   1.0]])
b = np.array([1.0, 2.0])
print("no pivoting:  ", solve_no_pivot(A, b))
print("np.linalg.solve:", np.linalg.solve(A, b))
print("condition number:", np.linalg.cond(A))
no pivoting:   [0. 1.]
np.linalg.solve: [1. 1.]
condition number: 2.6180339887498953

The problem is well conditioned; the algorithm manufactured the error. In the language of the floating point lessons, elimination without pivoting is unstable.

5. Partial pivoting, and the number that measures it

Partial pivoting fixes the example: before eliminating column kk, swap up the row whose entry in that column is largest in magnitude. Every multiplier then satisfies ∣ℓik∣≤1|\ell_{ik}| \le 1, and the factorisation becomes PA=LUPA = LU with PP a permutation.

Bounded multipliers do not quite bound everything. What controls the backward error is how large the entries of UU become relative to those of AA:

Definition: the growth factor of an elimination is ρ=max⁡ij∣uij∣ / max⁡ij∣aij∣\rho = \max_{ij}|u_{ij}| \,/\, \max_{ij}|a_{ij}|. Trefethen and Bau (Lecture 22) show the computed factors are exact for a matrix within roughly ρ⋅εmach\rho \cdot \varepsilon_{\text{mach}} of AA, relatively.

With partial pivoting, ρ\rho can be as large as 2n−12^{n-1}, a bound Wilkinson identified, and that worst case is reachable. Trefethen and Bau summarise the situation bluntly: Gaussian elimination with partial pivoting is unstable for certain matrices and stable in practice, because matrices with large growth almost never arise in applications. The next step builds one of the rare ones.

6. The matrix that breaks partial pivoting

Wilkinson's example has 1 on the diagonal, −1-1 below it, and a last column of ones. No row swap is ever triggered, and each step doubles the last column.

import numpy as np
from scipy.linalg import lu, qr, solve_triangular

n = 60
W = np.eye(n) - np.tril(np.ones((n, n)), -1)   # 1 on the diagonal, -1 below
W[:, -1] = 1.0                                  # last column all ones

P, L, U = lu(W)                                 # partial pivoting
print(f"growth factor {np.abs(U).max() / np.abs(W).max():.2e}, 2**59 = {2.0**59:.2e}")
print(f"cond(W) = {np.linalg.cond(W):.1f}")

x_true = np.random.default_rng(1).standard_normal(n)
b = W @ x_true
Q, R = qr(W)
for name, x in [("LU, partial pivoting", np.linalg.solve(W, b)),
                ("Householder QR", solve_triangular(R, Q.T @ b))]:
    err = np.linalg.norm(x - x_true) / np.linalg.norm(x_true)
    print(f"{name:21s} relative error {err:.1e}")
growth factor 5.76e+17, 2**59 = 5.76e+17
cond(W) = 26.8
LU, partial pivoting  relative error 5.6e-01
Householder QR        relative error 1.3e-15

The condition number is 26.8, so a stable method should lose about one or two digits. LU with partial pivoting loses all of them, because the growth factor hits exactly 2592^{59}. Householder QR, which uses orthogonal transformations that cannot grow entries, solves it to 10−1510^{-15}.

Gotcha: this is a demonstration, not a reason to abandon LU. QR costs twice the flops, and for the matrices that arise from real problems, partial pivoting's growth stays small. Libraries default to LU for that reason.

7. Symmetric positive definite: Cholesky

Many matrices in practice are symmetric positive definite (SPD): covariance matrices, normal-equation matrices, stiffness matrices from finite elements, the graph Laplacian plus a positive shift. For these the factorisation simplifies to

A=R⊤R,R upper triangular with positive diagonalA = R^\top R, \qquad R \text{ upper triangular with positive diagonal}

and three things improve at once, per Trefethen and Bau (Lecture 23):

  1. Half the work: 13n3\tfrac{1}{3}n^3 flops instead of 23n3\tfrac{2}{3}n^3, and half the storage, since only one triangle is kept.
  2. No pivoting needed: Cholesky is backward stable as is, because the entries of RR are bounded by the diagonal of AA.
  3. A free test: the algorithm takes a square root of each pivot, and a pivot that is not positive proves AA is not SPD. Attempting a Cholesky factorisation is the standard cheap check for positive definiteness.

In practice: scipy.linalg.cho_factor and cho_solve mirror the lu_factor and lu_solve pair. NumPy's np.linalg.cholesky raises LinAlgError on a matrix that is not positive definite, which is exactly the test in point 3.

8. Residual, error, and what to report

After solving, you can always compute the residual r=b−Ax^\mathbf{r} = \mathbf{b} - A\hat{\mathbf{x}}. You can almost never compute the error x^−x\hat{\mathbf{x}} - \mathbf{x}, since that needs the true answer. The condition number connects the two:

∥x^−x∥∥x∥  ≲  κ(A) ∥b−Ax^∥∥A∥ ∥x^∥\frac{\|\hat{\mathbf{x}} - \mathbf{x}\|}{\|\mathbf{x}\|} \;\lesssim\; \kappa(A)\,\frac{\|\mathbf{b} - A\hat{\mathbf{x}}\|}{\|A\|\,\|\hat{\mathbf{x}}\|}

The right-hand fraction is the normwise backward error from the Hilbert example. A backward stable solver keeps it near 10−1610^{-16}, so the attainable accuracy is set by κ(A)\kappa(A) alone. On the Hilbert matrix, 1.6×10131.6 \times 10^{13} times 10−1610^{-16} predicts an error up to about 2×10−32 \times 10^{-3}; the observed 8.7×10−58.7 \times 10^{-5} sits inside the bound, as it should.

In practice: report both numbers. A small backward error says the solver did its job; a large condition number says the inputs cannot support more digits. np.linalg.cond costs an SVD, so for large matrices use a cheap estimate from the LU factors, such as LAPACK's gecon, which scipy.linalg.solve uses to warn about ill-conditioned matrices.

9. Structure beats brute force

The 23n3\tfrac{2}{3}n^3 count assumes nothing about AA. Most large matrices have structure, and exploiting it changes the cost by orders of magnitude.

MatrixMethodSciPy / NumPy entry point
Dense, generalLU with partial pivotingnp.linalg.solve, scipy.linalg.lu_factor
Dense, SPDCholeskyscipy.linalg.cho_factor
Banded, bandwidth bbBanded LU, O(nb2)O(nb^2) work per Golub and Van Loan's Matrix Computationsscipy.linalg.solve_banded
TridiagonalThe Thomas algorithm, O(n)O(n)scipy.linalg.solve_banded with b=1b = 1
Sparse, generalSparse LU with a fill-reducing orderingscipy.sparse.linalg.splu, spsolve
Tall, least squaresQR or SVD, never the normal equationsnp.linalg.lstsq

A tridiagonal system with a million unknowns, which dense LU would treat as 6.7×10176.7 \times 10^{17} flops, is solved in a few million operations by the banded route. Ignoring structure is the most expensive mistake in this subject.

10. Fill-in: where direct methods run out

Factoring a sparse matrix creates nonzeros where AA had zeros, called fill-in. Reordering the unknowns first reduces it, but for a 2D grid it cannot remove it:

import scipy.sparse as sp
from scipy.sparse.linalg import splu

def poisson2d(N):
    T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(N, N))
    I = sp.identity(N)
    return (sp.kron(I, T) + sp.kron(T, I)).tocsc()

for N in (32, 64, 128):
    A = poisson2d(N)
    for order in ("NATURAL", "COLAMD"):
        F = splu(A, permc_spec=order)
        fill = F.L.nnz + F.U.nnz
        print(f"n={N*N:6d}  nnz(A)={A.nnz:6d}  {order:8s} nnz(L+U)={fill:9d}  ({fill / A.nnz:5.1f}x)")
n=  1024  nnz(A)=  4992  NATURAL  nnz(L+U)=    65598  ( 13.1x)
n=  1024  nnz(A)=  4992  COLAMD   nnz(L+U)=    37334  (  7.5x)
n=  4096  nnz(A)= 20224  NATURAL  nnz(L+U)=   524414  ( 25.9x)
n=  4096  nnz(A)= 20224  COLAMD   nnz(L+U)=   220624  ( 10.9x)
n= 16384  nnz(A)= 81408  NATURAL  nnz(L+U)=  4194558  ( 51.5x)
n= 16384  nnz(A)= 81408  COLAMD   nnz(L+U)=  1221240  ( 15.0x)

The matrix has five nonzeros per row at every size, yet the factors grow faster than nn under both orderings. Scale this to a 3D grid with millions of unknowns and the factors no longer fit in memory, while a dense matrix of order 10610^6 would need 8×10128 \times 10^{12} bytes, 8 TB at 8 bytes per IEEE 754 double. That is the point where iterative methods, the subject of the next lesson, take over.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. You must solve A x = b for 1000 different right-hand sides with the same dense 2000 by 2000 matrix A. What is the efficient approach?
    • Call np.linalg.solve 1000 times
    • Compute inv(A) once and multiply each b by it
    • Factor A once with lu_factor, then call lu_solve for each b
    • Use Cramer's rule for each right-hand side
  2. Elimination without pivoting returns a badly wrong answer for a matrix with condition number 2.6. What is the diagnosis?
    • The algorithm is unstable: a tiny pivot produced a huge multiplier
    • The problem is ill conditioned
    • Double precision is insufficient for 2 by 2 systems
    • The right-hand side was rounded on input
  3. What does the growth factor in Gaussian elimination measure?
    • The condition number of the permutation matrix
    • The number of row swaps performed
    • How much the fill-in increases the number of nonzeros
    • How large the entries of U become relative to those of A
  4. A solver reports a normwise backward error of 1e-16 on a matrix with condition number 1e10. About how accurate is the solution?
    • About 16 correct digits
    • About 6 correct digits
    • About 10 correct digits
    • No digits can be trusted
  5. Why does a Cholesky attempt serve as a test for positive definiteness?
    • It computes all eigenvalues as a by-product
    • It requires pivoting only when the matrix is indefinite
    • It needs the square root of each pivot, and a non-positive pivot proves the matrix is not positive definite
    • It fails whenever the matrix is ill conditioned

Related lessons

Math
advanced

Iterative Solvers: From Jacobi to Preconditioned Conjugate Gradient

When a matrix is too large to factor, solve Ax = b by improving a guess. See why Jacobi stalls on fine grids, how Krylov methods and conjugate gradient use the whole history, why iterations scale with the square root of the condition number, what preconditioning buys, and how to set and check tolerances.

10 steps·~15 min
Math
advanced

Stiff Equations, Stability Regions, and Adaptive Step Size

Why an ODE solver can blow up at step sizes accuracy would never demand. Learn stability regions on the test equation, what makes a problem stiff, how implicit methods and A-stability fix it at the cost of Newton solves, how BDF and Radau escape Dahlquist's barrier, and how adaptive solvers choose each step.

12 steps·~18 min
Math
advanced

Root Finding: Bisection, Newton, and Knowing When to Stop

Most equations have no formula for their solution, so computers chase roots with sequences. Compare bisection, secant, Newton and Brent's method by convergence order and guarantees, watch Newton fail, learn how accurate a root can be, and pick stopping tests that do not lie.

11 steps·~17 min
Math
intermediate

What a Differential Equation Says: Rates, Solutions, and Slope Fields

A differential equation is a local rule for change, not a formula for the answer. Learn to read and classify one, solve the exponential and logistic cases, know when a unique solution exists, turn any order into a first-order system, and step forward numerically with Euler and Runge-Kutta.

10 steps·~15 min