The same recipe matrix, a new right-hand side every day. Eliminate from scratch each day and 100 days of a 1,000 × 1,000 system cost 3.3 × 1010 steps. Factor once into L and U and they cost 4.3 × 108: 77 times less.
Press Next day, then switch the method and the size. Then we build, piece by piece, triangular solves, LU, pivoting, inverses, Cholesky, least squares and the condition number.
You need a little Python and matrix times vector. We build the rest from zero.
Based on Chapter 28, Matrix Operations, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Multithreaded Algorithms. Next: Linear Programming.
The 3 × 3 system is the page's running example. Step counts are the leading terms: n3/3 to eliminate or factor, n2 for the two triangular solves.
Chapter 0
Write a daily production plan as Ax = b, and see which part of the work repeats
A factory makes three chemicals from three raw materials. The recipes never change. Every morning a truck brings a new load of materials. You must decide how many liters of each chemical to make, so that nothing is left over.
Call the liters x1, x2, x3 and the delivered kilograms b1, b2, b3. Each material gives one equation. The matrix A holds the recipes: row i, column j is the kilograms of material i that one liter of chemical j uses. The plan is a system of linear equations, Ax = b.
Each equation in two unknowns is a line. The answer is the crossing. Drag the knobs until the lines are parallel.
Line 1 is 2x1 + x2 = 5. Line 2 is x1 + a22x2 = b2.
Parallel lines have no crossing, or a whole line of them. The matrix is then singular: no unique answer exists. A matrix with a unique answer for every b is nonsingular.
Gaussian elimination solves Ax = b by subtracting multiples of rows until the system is triangular. For n equations it costs about n3/3 multiply-add steps. That work depends only on A. Tomorrow, with a new b, plain elimination does all of it again.
Worked number: n = 1,000 and 100 deliveries. Eliminating each day costs 100 × (3.3 × 108 + 106) = 3.3 × 1010 steps. Factoring A once costs 3.3 × 108, and each day then costs 106: 4.3 × 108 in total, 77 times less.
The failure. Symptom: a solver call takes the same long time for every new b. Measure: time two calls; if both scale like n3, the solver factors A each time. Fix: factor once and keep the factors (in SciPy, lu_factor once, then lu_solve per b).
Chapter 1
Peel off one unknown per row, top down or bottom up
A lower-triangular matrix has only zeros above its diagonal. Its first row holds one unknown, so you read it off. The second row then holds one new unknown, and so on down. A unit lower-triangular matrix also has 1s on its diagonal.
Take the unit lower-triangular matrix L from this page's example and a right-hand side b. Call the unknown vector y, and the entry of L in row i, column j, lij.
y-i equals b-i minus the sum over j less than i of l-i-j times y-j.
Go down the rows. In row i, multiply each known y-j by its l-i-j, add those up, and subtract the total from b-i. What is left is y-i.
L has rows (1, 0, 0), (2, 1, 0), (3, 9, 1) and b = (6, 16, 46). Then y1 = 6, y2 = 16 − 2 × 6 = 4, and y3 = 46 − 3 × 6 − 9 × 4 = −8.
Pick forward (L, top down) or back (U, bottom up). Press Step. The row in use lights up, and its known values feed the new one.
The page's example. Warm entries are multipliers in L; purple entries are U.
An upper-triangular matrix U has zeros below its diagonal. Back substitution runs the same idea from the bottom row up. It divides by the diagonal entry uii, because U has no 1s there:
xi = (yi − Σj>i uij xj) / uii. Take U rows (2, 3, 1), (0, 1, 3), (0, 0, −8) and y = (6, 4, −8). Then x3 = −8 / −8 = 1, x2 = 4 − 3 = 1, x1 = (6 − 3 − 1) / 2 = 1.
Count the work. Row i uses i − 1 multiply-adds, so one triangle costs 0 + 1 + … + (n − 1) = n(n − 1)/2. Both triangles together cost about n2. For n = 1,000 that is 106 steps, against 3.3 × 108 to eliminate.
The failure. Symptom: back substitution returns inf or nan. Measure: print the diagonal of U and look for a 0. Fix: A is singular, or the factoring needed a row swap (Chapter 3).
Chapter 2
Keep every multiplier, and the elimination becomes two reusable triangles
Elimination zeroes the entries below each pivot, the diagonal entry of the column you clear. To clear row i in column k, it subtracts a multiplier times row k. The multiplier is the entry to clear divided by the pivot. Call it lik = aik / akk.
Then every entry aij to the right in row i changes:
a-i-j becomes a-i-j minus l-i-k times a-k-j.
For each column k, and each row i below the pivot: compute l-i-k, then subtract l-i-k times the pivot row from row i. Write l-i-k into L. What stays in the matrix becomes U.
A has rows (2, 3, 1), (4, 7, 5), (6, 18, 22). Column 1: l31 = 6 / 2 = 3, so a32 = 18 − 3 × 3 = 9 and a33 = 22 − 3 × 1 = 19. Column 2: l32 = 9 / 1 = 9, so a33 = 19 − 9 × 3 = −8.
Press Step. One entry below a pivot turns to 0, and its multiplier moves into L. Then try the matrix whose first pivot is 0.
The multipliers 2, 3 and 9 fill L below its 1s. The pivots 2, 1 and −8 sit on U's diagonal.
The result is the LU decomposition A = LU. Here L has rows (1, 0, 0), (2, 1, 0), (3, 9, 1). U has rows (2, 3, 1), (0, 1, 3), (0, 0, −8). Check row 3: 3 × (2, 3, 1) + 9 × (0, 1, 3) + (0, 0, −8) = (6, 18, 22).
To solve Ax = b, write LUx = b. Solve Ly = b, then Ux = y: the two triangles of Chapter 1. With b = (6, 16, 46) you get y = (6, 4, −8) and x = (1, 1, 1). The factoring costs about n3/3; it is the elimination itself. L and U also fit in A's own n2 cells: L's multipliers go below the diagonal, and its 1s need no storage.
The failure. Symptom: a division by zero in the first column. Measure: look at the pivot akk before you divide. Fix: swap in a row with a nonzero entry; that is pivoting, next.
Chapter 3
Swap the biggest entry to the pivot, and every multiplier stays at 1 or less
A zero pivot stops elimination. A tiny pivot is worse: it does not stop, it quietly ruins the answer. Take these two equations, with ε = 0.0001:
ε x1 + x2 = 1 and x1 + x2 = 2. The true answer is x1 = 1.0001, x2 = 0.9999.
Suppose the computer keeps 3 significant digits. The multiplier is 1 / 0.0001 = 10,000. Row 2 becomes (1 − 10,000) x2 = 2 − 10,000, and both sides round to −1.00 × 104. So x2 = 1.00, and row 1 gives x1 = (1 − 1.00) / 0.0001 = 0. That is 100% wrong.
Shrink ε and the digits the computer keeps. Then turn on pivoting, which swaps the rows first.
Every operation rounds to the chosen number of significant digits. The double setting does not round.
Partial pivoting fixes this. Before clearing column k, find the entry with the largest absolute value at or below the diagonal, and swap its row up. Record the swaps in a permutation matrix P: the identity matrix with its rows reordered.
P A equals L U.
Reorder the rows of A by P, then factor as before. To solve Ax = b, reorder b the same way: solve Ly = Pb, then Ux = y. CLRS calls this the LUP decomposition.
B has rows (1, 2, 3), (4, 5, 6), (7, 8, 0). Column 1 picks 7, column 2 picks 6/7 ≈ 0.857. PB has rows (7, 8, 0), (1, 2, 3), (4, 5, 6). L's multipliers are 1/7, 4/7 and 1/2, all at most 1. U's diagonal is 7, 0.857, 4.5.
Why it works: the largest entry is the pivot, so every multiplier has size at most 1. Small multipliers keep rounding errors from being blown up. The cost is about n2/2 comparisons, nothing next to n3/3. In the worst case U's entries can still grow by a factor of 2n−1, but such matrices are rare in practice.
The failure. Symptom: a solver gives answers far off on some inputs and fine on others. Measure: compute the residual b − Ax; with no pivoting it can be large. Fix: always pivot. LAPACK's general solver, used by numpy.linalg.solve, does.
Chapter 4
Solve for one column of the inverse at a time, and read the determinant off U
The inverse A−1 is the matrix with A A−1 = I, the identity. Look at column j of that equation. A times column j of A−1 equals ej, the column of I with a 1 in place j. So the inverse is n systems with one A. Factor once, then do n pairs of triangular solves.
Press Next column. Each press solves L y = ej and U x = y with the factors from Chapter 2.
The page's example A. The last line multiplies U's diagonal.
The cost is n3/3 to factor plus n × n2 for the solves: about n3 in all. To get one answer x, the inverse route also multiplies A−1b. At n = 1,000 that is 1.3 × 109 steps against 3.3 × 108 for one LU solve: four times the work. It also tends to lose more digits to rounding. Solve; do not invert.
The determinant comes for free. The determinant of a triangular matrix is the product of its diagonal. det(L) = 1. Each row swap flips the sign. Call the number of swaps s.
det of A equals minus one to the s, times u-one-one times u-two-two, and so on up to u-n-n.
Factor PA = LU. Multiply the pivots on U's diagonal. Flip the sign if the number of swaps s is odd.
For A, s = 0 and the pivots are 2, 1, −8: det(A) = 2 × 1 × (−8) = −16. For B of Chapter 3, s = 2 and the pivots are 7, 6/7, 4.5: det(B) = 7 × 6/7 × 4.5 = 27.
The textbook cofactor expansion has n! terms; at n = 20 that is 2.4 × 1018. LU gives the determinant in n3/3 steps.
The failure. Symptom: A−1 has huge entries and A A−1 is visibly not I. Measure: compute the largest entry of A A−1 − I. Fix: A is close to singular (Chapter 8); solve the system you need instead of inverting.
Chapter 5
Hide a product inside an inverse, and an inverse inside products
Multiplying two n × n matrices by the school method costs n3. Strassen's method (CLRS Chapter 4) costs about n2.81. CLRS proves that inversion costs the same as multiplication, up to a constant factor. A faster multiply gives a faster inverse, and the other way round.
The first direction is a trick. Build a 3n × 3n matrix M from the identity I and the two matrices A and B. Invert M. The product AB appears in the top-right block.
Each entry stands for an n × n block; here n = 1, so A and B are numbers. Drag them and watch the corner of M−1.
With real blocks, the same picture holds: 0 and I are n × n blocks of zeros and the identity.
M = [I A 0; 0 I B; 0 0 I] has inverse [I −A AB; 0 I −B; 0 0 I]. With A = 2 and B = 3, the corner is 6.
So if you can invert a 3n matrix in time I(3n), you can multiply in that time. The other direction (CLRS Theorem 28.2) splits the matrix into four blocks and inverts recursively. Each level needs a few multiplications, so inversion costs a constant times the cost of multiplying. LUP decomposition reduces to multiplication the same way (Bunch and Hopcroft, 1974).
Call the true exponent of matrix multiplication ω: the smallest power with an nω method. Reading the input already takes n2, so ω is at least 2. Research has pushed the upper bound below 2.372. Nobody knows if ω = 2. Real libraries still use blocked n3 methods, because their constants are small and they use the cache well.
The failure. Symptom: a recursive block inverse breaks when n is odd. Measure: check whether n is a power of 2. Fix: pad A with an identity block up to the next power of 2, as CLRS does. That at most doubles n, a constant factor.
Chapter 6
Use symmetry to factor with half the work and no row swaps
A matrix is symmetric when A equals its transpose: entry (i, j) equals entry (j, i). It is positive-definite when xTAx > 0 for every nonzero vector x. Both together give a symmetric positive-definite (SPD) matrix. Covariance matrices are SPD when no variable is a mix of the others, and so is ATA when A's columns are independent.
CLRS shows that LU on an SPD matrix never meets a zero pivot, so it needs no swaps. Symmetry goes further: U is a scaled copy of LT. The Cholesky decomposition writes A = LLT, with L lower-triangular and a positive diagonal. Call L's entries lij and A's entries aij.
l-j-j equals the square root of a-j-j minus the sum over k less than j of l-j-k squared.
Take the diagonal entry a-j-j. Subtract the squares of the entries already in row j of L. The square root of what is left is l-j-j. If what is left is 0 or negative, A is not SPD.
A has rows (4, 2, 2), (2, 5, 3), (2, 3, 6). Row 3 of L starts with l31 = 1 and l32 = 1, so l33 = √(6 − 1 − 1) = √4 = 2.
Entries below the diagonal use the same pattern, divided by the diagonal of column j:
lij = (aij − Σk<j lik ljk) / ljj. Example: l32 = (3 − 1 × 1) / 2 = 1. Here L has rows (2, 0, 0), (1, 2, 0), (1, 1, 2).
Press Step to fill L one entry at a time. Then lower the corner a33 until the square root has nothing left to take.
The last step takes the root of a33 − 2. At a33 = 2 or below, A is not positive-definite.
Cholesky computes only one triangle, so it costs about n3/6, half of LU. It needs no pivoting. It is also the cheapest test for SPD: try it, and see if a square root fails.
The failure. Symptom: numpy.linalg.cholesky raises LinAlgError on a covariance matrix. Measure: count samples against variables; fewer samples than variables makes the covariance singular. Fix: get more data, or add a small multiple of I to the diagonal.
Chapter 7
When no line passes through every point, find the one that misses least
Four measurements: (1, 2), (2, 3), (3, 6), (4, 8). You want a line y = c0 + c1t. Each point gives one equation, so you have 4 equations and 2 unknowns. No line passes through all four. We call such a system overdetermined.
Write it as Ax ≈ b. Row i of A is (1, ti), b holds the measured y values, and x = (c0, c1). The residual r = b − Ax is the miss at each point. Least squares picks the x that makes the sum of squared residuals smallest. Setting its derivative to 0 gives 2AT(Ax − b) = 0, and so:
A-transpose A x equals A-transpose b.
Form the small n × n matrix A-transpose A and the vector A-transpose b. Solve that square system for x, with Cholesky when A's columns are independent. These are the normal equations.
ATA has rows (4, 10), (10, 30). ATb = (19, 58), since 2 + 3 + 6 + 8 = 19 and 2 + 6 + 18 + 32 = 58. Solving gives c1 = 2.1 and c0 = −0.5: the line y = −0.5 + 2.1t.
The residuals are 0.4, −0.7, 0.2 and 0.1; their squares add to 0.7. They also sum to 0. That is ATr = 0 at work: the residual is normal, meaning perpendicular, to every column of A. The fit is the shadow of b on the space the columns span.
Tap the plot to add points. Drag the degree. Pink bars are residuals. Watch the condition number of ATA as the degree climbs.
The fit uses a QR solve for the curve. The condition number is of ATA for t from 0 to 10, the matrix the normal equations would factor. The noisy curve comes from a formula plus fixed noise, not from data.
A polynomial of degree d has d + 1 coefficients, so A gets columns 1, t, t2, …, td. The normal matrix stays (d + 1) × (d + 1), whatever the number of points. With 1,000 points and degree 3 it is 4 × 4. CLRS writes the answer as x = A+b, where A+ = (ATA)−1AT is the pseudoinverse. In code you still solve; you do not invert.
The failure. Symptom: a high-degree fit passes through every point and swings wildly between them. Measure: hold out a few points and compare their residuals with the training residuals. Fix: lower the degree, or get more points per coefficient.
Chapter 8
Measure how much a small change in b can move x, and keep the normal equations from squaring it
Two lines that cross at a steep angle pin down the answer. Two lines that are nearly parallel do not: nudge one a little, and the crossing slides far along them. No algorithm can fix that. It is a property of the problem.
Bring the lines closer to parallel. Then nudge b2. The pink arrow shows how far the answer moves.
The system is x1 + x2 = 2 and x1 + (1 + δ)x2 = 2 + δ + nudge. Without the nudge the answer is (1, 1).
Call the length of a vector its norm, written with double bars. A stretches some directions most and some least; the ratio of the largest stretch to the smallest is the condition number κ(A). Call the nudge to b δb, and the move it causes in x δx.
The norm of delta-x over the norm of x is at most kappa of A times the norm of delta-b over the norm of b.
Take the relative error in b. Multiply it by kappa of A. The relative error in x is at most that. With about 16 digits in a double, expect to lose about the log, base 10, of kappa.
A has rows (1, 1), (1, 1.0001), so κ(A) ≈ 40,000. With b = (2, 2.0001), x = (1, 1). Change b2 to 2.0002, a relative change of 3.5 × 10−5. Now x = (0, 2): a relative change of 1, under the bound 40,000 × 3.5 × 10−5 = 1.41.
Now the trap. The normal equations factor ATA, and its condition number is the square:
κ(ATA) = κ(A)2. For the A above: 40,0002 = 1.6 × 109, so about 9 of 16 digits are lost instead of about 5.
Three fixes, in order of cost:
numpy.linalg.lstsq uses it.The failure. Symptom: regression coefficients swing when you drop one data point. Measure: numpy.linalg.cond(A); above about 108 the normal equations keep no digits. Fix: remove near-duplicate columns, scale the columns, and solve with QR or SVD.
Chapter 9
Keep the choices, the numbers, the checks and the core code on one page
Factor once, solve many times. LUP handles any nonsingular square matrix in n3/3, then n2 per right-hand side. Cholesky halves that for SPD matrices. Least squares turns a tall system into a small square one, and the condition number says how many digits survive.
| Factorization | Needs | Leading cost | Use it for |
|---|---|---|---|
| PA = LU (LUP) | square, nonsingular | n3/3 | general Ax = b, determinant, inverse |
| A = LLT (Cholesky) | symmetric positive-definite | n3/6 | covariances, normal equations, SPD test |
| A = QR | m ≥ n, independent columns | about 2× the normal equations | least squares without squaring κ |
| SVD | any matrix | more than QR | rank-deficient least squares, κ, the pseudoinverse |
| Term | Meaning | Number on this page |
|---|---|---|
| Forward substitution | solve L y = b top down | y = (6, 4, −8) |
| Back substitution | solve U x = y bottom up | x = (1, 1, 1) |
| Multiplier lik | aik / akk, stored in L | 2, 3, 9 |
| Pivot | diagonal entry you divide by | 2, 1, −8 |
| Partial pivoting | swap the largest entry up; |lik| ≤ 1 | ε = 0.0001, 3 digits: x1 = 0 without it |
| Determinant | (−1)s times the pivots | det(A) = −16 |
| Inverse | n solves with columns of I | column 1 = (−4, 3.625, −1.875) |
| ω | exponent of matrix multiplication | 2 ≤ ω < 2.372 |
| Cholesky | A = LLT | L diagonal 2, 2, 2 |
| Normal equations | ATAx = ATb | y = −0.5 + 2.1t, squared residuals 0.7 |
| Condition number | largest over smallest stretch | 40,000, squared to 1.6 × 109 |
pythonimport numpy as np def lup_decompose(A): """CLRS LUP-DECOMPOSITION: L and U packed in one array, plus the row order.""" a = np.array(A, dtype=float) n = len(a) perm = list(range(n)) for k in range(n): p = k + int(np.argmax(np.abs(a[k:, k]))) # largest entry in column k if a[p, k] == 0: raise ValueError("singular matrix") a[[k, p]] = a[[p, k]] # swap rows (the L part too) perm[k], perm[p] = perm[p], perm[k] a[k+1:, k] /= a[k, k] # multipliers l_ik, kept below the diagonal a[k+1:, k+1:] -= np.outer(a[k+1:, k], a[k, k+1:]) # a_ij -= l_ik * a_kj return a, perm def lup_solve(lu, perm, b): n = len(lu) y = np.zeros(n) for i in range(n): # forward: L y = P b y[i] = b[perm[i]] - lu[i, :i] @ y[:i] x = np.zeros(n) for i in reversed(range(n)): # back: U x = y x[i] = (y[i] - lu[i, i+1:] @ x[i+1:]) / lu[i, i] return x def cholesky(A): n = len(A) L = np.zeros((n, n)) for j in range(n): r = A[j][j] - L[j, :j] @ L[j, :j] # what is left under the root if r <= 0: raise ValueError("not positive definite") L[j, j] = np.sqrt(r) for i in range(j + 1, n): L[i, j] = (A[i][j] - L[i, :j] @ L[j, :j]) / L[j, j] return L A = [[2, 3, 1], [4, 7, 5], [6, 18, 22]] lu, perm = lup_decompose(A) print(lup_solve(lu, perm, np.array([6., 16, 46]))) # [1. 1. 1.] print(cholesky([[4, 2, 2], [2, 5, 3], [2, 3, 6]])) # rows (2,0,0) (1,2,0) (1,1,2) t = np.array([1., 2, 3, 4]); y = np.array([2., 3, 6, 8]) X = np.column_stack([np.ones(4), t]) print(np.linalg.lstsq(X, y, rcond=None)[0]) # [-0.5 2.1]
Now press Present or Teach. Explain from memory why a triangle solves in n2 and what L stores. Then say why the pivot should be the largest entry, and why the normal equations lose digits. Then go back to the hero, set n = 1,000, and say why the LU line stays flat.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 28, Matrix Operations (third edition numbering). The LUP method, the inversion theorems and the normal equations follow the book. Cholesky, QR, SVD and ridge are standard numerical linear algebra; see L. N. Trefethen and D. Bau, Numerical Linear Algebra. The example matrices, devices and step counts are our own.