9.2 Gaussian elimination and LU with partial pivoting
The previous section, Vectors, matrices, row-major layout, and matmul, let you multiply matrices. It did not let you undo a multiplication: given and , find the with . That is the core step of every second-order method you will meet. Logistic regression by IRLS, in Logistic regression (IRLS), ROC-AUC, calibration (the classifier behind the usage-policy head), solves one linear system per iteration. Newton’s method solves one per step. And the section after this one, Eigenvalues, power iteration, and the spectral radius, finds the eigenvalue of a matrix nearest a chosen number by solving with the same matrix again and again.
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Logistic regression: a model in which the log-odds are linear in the features. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- IRLS: iteratively reweighted least squares, Newton’s method on the logistic loss, where each step is a weighted least-squares solve with weights . Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Row-major layout: storage in which each row of a matrix is contiguous in memory. Read more: 9.1 Vectors, matrices, row-major layout, and matmul
- Unit roundoff: , the largest relative error of a single round-to-nearest. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Inverse iteration: power iteration on , finding the eigenvalue nearest the shift . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot in AI Engineering
- Inverse permutation: (
inv_perm): the map from each assignment to its sorted slot, used to put outputs back. Read more: 13.8 Mixture of Experts in AI Engineering - Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Inverse matrix / invertible matrix: undoes , with ; it exists exactly when , and in practice you solve with a factorization instead of forming it. Read more: Chapter 9: Linear Algebra
Calling np.linalg.solve would work. This section builds the method from first principles instead, so you can see why it is fast (factor once, solve many times) and why the naive version silently returns garbage on perfectly ordinary matrices. By the end you will have lu(A), which returns with , and lu_solve(P, L, U, b), which solves by two triangular solves. The solution is lu.py and its contract is lu.pyi. Nothing needs to be built first, but the matrix product and row-major layout from the previous section are assumed.
Learning objectives
- Carry out Gaussian elimination with partial pivoting by hand and read off , , and with .
- Explain why the multipliers are exactly the entries of , and why pivoting bounds them by 1.
- Show, with a concrete pivot, how elimination without pivoting loses every digit of the answer.
- Solve by forward and back substitution, and say why a zero pivot must raise.
- Compare the cost of factoring () with the cost of each solve ().
Notation
Section titled “Notation”The section uses a small set of symbols throughout:
| Symbol | Meaning | Type / shape |
|---|---|---|
| a square matrix, its entries | float64[n, n] | |
| the unknown and the right-hand side of | float64[n] or [n, k] | |
| unit lower triangular: ones on the diagonal, zeros above | float64[n, n] | |
| upper triangular: zeros below the diagonal | float64[n, n] | |
| a permutation matrix: the identity with its rows reordered | float64[n, n] | |
| the multiplier that eliminates entry , stored in | scalar | |
| the -th pivot | scalar | |
| float64 unit roundoff, |
Elimination is a sequence of row operations
Section titled “Elimination is a sequence of row operations”Subtracting times row from row does not change the solution set of , provided you do the same to : it combines two true equations into a third. Gaussian elimination uses that operation to clear the entries below the diagonal, one column at a time. For column , the pivot is , and for each row ,
After columns the matrix is upper triangular. That is .
The multipliers form L
Section titled “The multipliers form L”Elimination looks like a procedure, but it is also a factorization. The row operation “row minus times row ” is multiplication on the left by , the identity with at position . Its inverse is : add the row back. Elimination computes , so
and the product of those inverses, taken in this order, is simply the identity with every multiplier placed at position . No arithmetic is needed to form : you write each multiplier where it was used. is the record of elimination, which is what lets you replay it on any later.
Pivoting
Section titled “Pivoting”So far the procedure divides by , and nothing guarantees that is non-zero. The matrix is invertible, yet its first pivot is 0. Swapping the two rows fixes it, since equations may be listed in any order.
A pivot that is merely small is worse, because nothing fails visibly. Take :
Pivoting on gives , and rounds to . The 1 in is lost, because the spacing of float64 numbers near is about . Back substitution then gets and . Every digit of is wrong.
Partial pivoting fixes both problems. For column it chooses the row with the largest and swaps it into row before eliminating. Then every multiplier satisfies , row operations never amplify entries by more than a factor 2 per step, and in practice elimination with partial pivoting is backward stable: the computed solves a system with a small multiple of . On the system, the 1, 1 row becomes the pivot, , keeps its information, and back substitution returns .
Three details make pivoting right, and each is a place where implementations go wrong:
- Search rows and below only. Rows above are finished pivot rows.
- Compare absolute values. is a better pivot than .
- Swap the whole rows of the working matrix, and also the multipliers already stored in for those two rows (columns to ). A multiplier belongs to its equation, and the equation moved. ’s diagonal stays where it is.
Ties go to the lowest row index (np.argmax returns the first maximum), which makes deterministic. If the best is 0, the whole column below the diagonal is already zero: there is nothing to eliminate, so skip it. The matrix is then singular, and carries a 0 on its diagonal.
Permutation matrices and solving
Section titled “Permutation matrices and solving”With pivoting in place, you need a way to record the swaps and use them when solving. Keep an array perm where row of the permuted matrix is row perm[i] of . The permutation matrix has , so . is orthogonal, , and in general ; a 3-cycle is the smallest example.
With , the system becomes , solved in two triangular steps:
Forward substitution divides by nothing, because has a unit diagonal. Back substitution divides by each pivot, so a zero pivot means the system has no unique solution and lu_solve raises. Several right-hand sides at once ( of shape ) use the same formulas column by column.
What it costs
Section titled “What it costs”Eliminating column updates an block with one multiply and one subtract per entry, so the factorization costs floating-point operations. Each triangular solve costs about . For , that is about operations to factor and per solve. That 300-fold gap is why inverse iteration in Eigenvalues, power iteration, and the spectral radius factors once and solves at every step.
Working it by hand
Section titled “Working it by hand”Now put it all together on a 3 by 3 system:
Column 0. The candidates are ; the largest absolute value is in row 1, so swap rows 0 and 1 (perm = [1, 0, 2]). The pivot is 4, and the multipliers are and :
Column 1. The candidates in rows 1 and 2 are and : a tie, so row 1 stays. and . The factors are
Check one entry of : row 2 of times column 0 of is .
Solve. . Forward: , , . Back: , , . So , and indeed , , . Every number here is a small dyadic fraction, so the solution reproduces them exactly.
Designing the API
Section titled “Designing the API”The interface splits factoring from solving, because that split is what makes the factor-once pattern possible:
def lu(A: ArrayLike) -> tuple[NDArray, NDArray, NDArray]: """P, L, U (float64 [n, n]) with P @ A == L @ U; |L| <= 1; ties to the lowest row; zero columns skipped (singular A still factors). A is not modified."""
def lu_solve(P: ArrayLike, L: ArrayLike, U: ArrayLike, b: ArrayLike) -> NDArray: """x with A @ x == b for b of shape [n] or [n, k]. ValueError on a zero pivot."""lu never raises on a singular matrix: a singular matrix still has a valid factorization with a zero on ‘s diagonal, and that zero is useful information, since it makes the rank deficiency visible. Only the solve needs to divide by the pivot, so that is where the error belongs. Neither function modifies its inputs, because callers reuse .
Building it step by step
Section titled “Building it step by step”The reasoning chain runs straight from the principles. Elimination only ever subtracts multiples of a pivot row from rows below it, so the work is a loop over columns , each updating the trailing block U[k+1:, k:]. The multipliers are exactly the entries of , so the solution writes each one into L[i, k] at the moment it is computed; no separate pass forms . Dividing by the pivot is safe and stable only if the pivot is the largest among the rows still being worked on. That forces three things: search U[k:, k] (not the whole column), compare absolute values, and swap the stored multipliers in L[:, :k] with the rows. A column whose best pivot is 0 has nothing to eliminate; skipping it, rather than raising, lets a singular matrix factor and leaves the 0 on ‘s diagonal where lu_solve can see it. Swaps are cheap to record as an index array perm and convert to once at the end. Solving replays elimination on and then undoes from the bottom row up, checking for a zero pivot before any division.
The factorization works on a float64 copy so the caller’s A survives:
def lu(A: ArrayLike) -> tuple[NDArray, NDArray, NDArray]: U = np.array(A, dtype=np.float64) # a copy: the caller's A is never touched if U.ndim != 2 or U.shape[0] != U.shape[1]: raise ValueError(f"lu: A must be a square matrix, got shape {U.shape}") n = U.shape[0] L = np.eye(n) perm = np.arange(n) # row i of P A is row perm[i] of AEach column picks its pivot from rows and below, by absolute value, ties to the first. np.argmax on the slice returns an offset into that slice, so adding k converts it back to a row index of U:
for k in range(n - 1): p = k + int(np.argmax(np.abs(U[k:, k]))) # offset by k: rows above are finished if U[p, k] == 0.0: continue # the column is already zero below k: nothing to eliminateThe swap moves the working rows, the multipliers already stored for those rows, and the permutation record. Only columns k: of U need to move, since columns left of k are already zero in both rows; only columns :k of L hold multipliers, and the unit diagonal stays in place:
if p != k: U[[k, p], k:] = U[[p, k], k:] L[[k, p], :k] = L[[p, k], :k] # a multiplier belongs to its equation perm[[k, p]] = perm[[p, k]]Elimination of the whole column is one vectorised rank-1 update. On the worked example at this computes m = [0.5, -0.5] and turns rows 1 and 2 into and :
m = U[k + 1 :, k] / U[k, k] # |m| <= 1 thanks to the pivot choice L[k + 1 :, k] = m # store with a + sign: row_i -= m * row_k U[k + 1 :, k:] -= np.outer(m, U[k, k:]) U[k + 1 :, k] = 0.0 # exactly zero by construction, not just rounded P = np.zeros((n, n)) P[np.arange(n), perm] = 1.0 # P[i, perm[i]] = 1, so (P A)[i] = A[perm[i]] return P, L, UThe solve validates shapes, refuses a zero pivot before dividing, and runs the two substitutions. Because y is indexed by its first axis only, the same loop handles b of shape [n] and [n, k]:
d = np.diag(U) if np.any(d == 0.0): raise ValueError("lu_solve: U has a zero pivot, A is singular") # Forward substitution, L y = P b: unit diagonal, no division. y = P @ b # P, not P.T: replays the row swaps on b for i in range(n): y[i] = y[i] - L[i, :i] @ y[:i] # Back substitution, U x = y, from the last row up. x = y # in place: y[i] is no longer needed once x[i] is set for i in range(n - 1, -1, -1): x[i] = (x[i] - U[i, i + 1 :] @ x[i + 1 :]) / d[i] return xP @ b allocates a new array, so the caller’s b is not modified either. The full solution is lu.py.
Why this design
Section titled “Why this design”The cost is flops to factor, about per right-hand side, and memory for the factors. Separating lu from lu_solve is what lets inverse iteration and IRLS pay the cubic cost once.
You might be tempted to invert instead. Forming costs about and is less accurate than solving with the factors, and it throws away the zero-pivot signal. Complete pivoting, which searches the whole trailing block for the largest entry, gives a tighter growth bound but costs comparisons and a column permutation as well; partial pivoting is backward stable in practice and is what LAPACK uses. Returning as a dense matrix matches the contract and makes directly checkable; production code returns the perm vector instead, and the solution keeps it internally for the same reason. The one tradeoff knowingly accepted is speed: the loops are Python-level over and , with NumPy doing each row or block. That is slow for large but makes every step of the algorithm visible.
What can go wrong
Section titled “What can go wrong”The test cases a correct solution must pass map directly onto the ideas above. The hand example must reproduce , , and exactly, which pins the pivot and tie rules and the order of forward then back substitution. On random matrices of sizes 1 to 12, the structural properties every caller relies on must hold: , a permutation, unit lower with , and upper. The answers must agree with np.linalg.solve for one and three right-hand sides with up to 40, which is what IRLS needs.
The boundary cases are where naive code breaks. The zero leading pivot must factor and solve, which shows pivoting is required, not optional. The system must give . A negative candidate must beat as the pivot. A large entry in a finished row must not be chosen, because the search covers rows and below only. A rank-2 matrix and the zero matrix must factor while solving with them raises. must be unchanged after the call, and non-square inputs or a wrong-length must raise. Finally, a 3-cycle permutation checks that the solve uses and not : is the inverse permutation and gives the same result only when is its own inverse (a product of disjoint swaps).
The common mistakes, their symptoms, and the line that prevents each are collected here:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| no pivoting at all | division by zero on invertible matrices, or every digit lost to a tiny pivot | always swaps the largest into the pivot row |
| choosing the largest value instead of the largest absolute value | multipliers above 1 and error growth | searches np.abs(U[k:, k]) |
| swapping rows of but not the multipliers already in | as soon as a later column swaps | swaps L[[k, p], :k] with the rows |
| applying to instead of | right answers whenever is its own inverse, wrong otherwise | starts the forward pass from y = P @ b |
| forgetting to divide by the pivot in back substitution | scaled wrongly except where pivots are 1 | divides each back-substitution row by d[i] |
| storing the multiplier with the wrong sign | stores m itself in L and subtracts outer(m, row_k) | |
| dividing by a zero pivot when solving | inf and nan instead of an error | checks np.any(d == 0.0) before any division and raises |
| searching the whole column for the pivot | a finished row is swapped back down | searches only U[k:, k] and offsets by k |
| eliminating in the caller’s array | the next solve with uses | works on np.array(A, dtype=np.float64), a copy |
Warning: Forgetting to swap the stored multipliers passes every test in which only one swap happens. The bug shows up only when a later column swaps again, so test with matrices that need several swaps.
Where this leads
Section titled “Where this leads”The next consumer is Eigenvalues, power iteration, and the spectral radius, whose inverse_iteration factors once and calls lu_solve at every step. Later, Logistic regression (IRLS), ROC-AUC, calibration solves at every iteration of logistic regression, and Newton steps in optimization solve with the Hessian.
Further reading
Section titled “Further reading”- LAPACK
dgetrf(SRC/dgetrf.f,dgetrf2.f): a blocked, right-looking factorization that spends almost all its time in matrix-matrix products, so it runs near the speed of GEMM. - LAPACK
dgetrsandscipy.linalg.lu_solve(scipy/linalg/_decomp_lu.py): triangular solves with many right-hand sides at once. - Rook and complete pivoting (Higham, ch. 9): stronger growth bounds at extra search cost.
- Sparse LU (SuperLU, UMFPACK;
scipy.sparse.linalg.splu): reorders rows and columns to keep and sparse. - Cholesky for symmetric positive definite systems (LAPACK
dpotrf): half the work and no pivoting needed; the natural choice for IRLS’s . - Trefethen and Bau, Numerical Linear Algebra, lectures 20 to 22 (elimination, pivoting, stability); Strang, Introduction to Linear Algebra, ch. 2; Higham, Accuracy and Stability of Numerical Algorithms, ch. 9.
Key terms
Section titled “Key terms”- Pivot: the diagonal entry that elimination divides by in column .
- Multiplier: , the amount of the pivot row subtracted from row ; stored in .
- Unit lower triangular: lower triangular with ones on the diagonal.
- Partial pivoting: swapping the row with the largest absolute entry (among rows and below) into the pivot position before eliminating.
- Permutation matrix: the identity with its rows reordered; orthogonal, with .
- Backward stable: the computed answer is the exact answer to a slightly perturbed problem, with a small multiple of .
Summary
Section titled “Summary”- Gaussian elimination turns into an upper triangular system by subtracting multiples of a pivot row from the rows below it; the multipliers form a unit lower triangular and the result is , with when no rows move.
- Partial pivoting swaps the row with the largest into the pivot position, so every ; the swaps form and .
- Without pivoting, a zero pivot stops elimination on an invertible matrix and a tiny one destroys the answer.
- Factor once in operations; each new right-hand side then costs only : forward substitution , back substitution .
- A singular matrix still factors, with a zero on ‘s diagonal; solving with it must fail loudly.
Review questions
Section titled “Review questions”-
Why does the pivot search use
U[k:, k]and addkto the result?Answer
Rows above are finished pivot rows; swapping one of them back down would undo earlier elimination.
np.argmaxon the slice returns an offset into that slice, sokconverts it back to a row index ofU. -
Why must
L[[k, p], :k]be swapped along with the rows ofU?Answer
Each stored multiplier says how much of an earlier pivot row was subtracted from a particular equation. When that equation moves to a different row, its history must move with it, or reconstructs the wrong rows and after the first later swap.
-
On the system, what does pivoting change, number by number?
Answer
Row 1 (the
1, 1row) becomes the pivot, so instead of . Then keeps its information, and back substitution gives instead of . -
Why does
luskip a zero column instead of raising, whilelu_solveraises?Answer
A singular matrix still has a valid factorization with a zero on ‘s diagonal; that is useful information (the rank deficiency is visible). Only the solve needs to divide by the pivot, so that is where the error belongs.
-
Why
y = P @ band notP.T @ b?Answer
means the factored equations are in the order
perm; becomes . is the inverse permutation and gives the same result only when is its own inverse (a product of disjoint swaps), so a 3-cycle exposes the difference. -
For , roughly how many operations does factoring cost compared with one solve, and what design does that justify?
Answer
About to factor and per solve, a 300-fold gap. It justifies separating
lufromlu_solveso a caller that solves many times with the same matrix factors only once.