Computing with Real Numbers
With rounding in every operation, which computed answers can be trusted?
The part opens with the ten algorithms of the twentieth century, eight of them numerical, and with two equations whose answer is almost exactly (1, 1): elimination as taught returns x1 = 0, and swapping the rows first returns 1 and 1. The problem was well conditioned and the algorithm unstable, and the part is built on that separation. The condition number belongs to the problem, backward error to the algorithm, and the forward error is at most their product: on Hilbert systems the backward error stays near rounding level while the answer loses every digit by size 12. Elimination becomes LU with pivoting, whose growth can reach 2^(n-1) and almost never does. Householder's mirrors solve least squares without squaring the condition number, the SVD regularizes a blur, and the shifted QR algorithm finds eight eigenvalues in 16 iterations, not 623. Conjugate gradients and multigrid then solve Poisson's equation, the second at a cost proportional to the unknowns. Newton's fractal, Runge's phenomenon and Chebyshev points, quadrature, stiff and symplectic integrators and the BLAS follow, and the frontier is randomized and low-precision numerics, with the missing theorem for partial pivoting.
What you need. Matrices, derivatives and Taylor series; Part 4's floating-point numbers are the starting point.
- Mathematics, ideas and history
- conditioning and backward stability, LU and pivoting, Householder QR, the QR algorithm, CG and Krylov, multigrid, Newton's fractal, stiffness, BLAS
- What we build or compute
- the top-ten algorithms of the century, run
What you will be able to do
Degree
- Compute the relative condition number of a function and say how many digits it costs.
- Solve a small system by LU with partial pivoting and explain what the tiny pivot did without it.
- Run bisection, the secant method and Newton's method on one equation and compare the digits gained per step.
Graduate
- Derive forward error <= kappa x backward error and compute a solve's backward error from its residual.
- Derive Householder QR and explain why the normal equations square the condition number.
- State conjugate gradients' bound and multigrid's work recurrence, and check both on Poisson's equation.
Research
- Explain why a randomized SVD with a few extra columns matches the best rank-k error, and what power steps add.
- State what smoothed analysis says about elimination's growth factor and which theorem for partial pivoting is still missing.
Industry
- Choose a fill-reducing ordering for a sparse factorization and measure the factor's nonzeros.
- Recognize a stiff problem from an explicit solver's step count and switch to an implicit method.
- Use mixed-precision iterative refinement, and say at which condition number it stops working.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 50 min · Research 52 min · Industry 24 min.
- 0Ten algorithms of the centuryDegree1 min
- 1Conditioning and stabilityDegree4 min
- 2Backward error analysisGraduate2 min
- 3Gaussian eliminationDegree3 min
- 4Least squares and QRGraduate3 min
- 5The SVDGraduate3 min
- 6Eigenvalues: the QR algorithmGraduate3 min
- 7Conjugate gradientsGraduate3 min
- 8Sparse matricesIndustry3 min
- 9MultigridGraduate4 min
- 10Roots and Newton's fractalDegree3 min
- 11ApproximationGraduate2 min
- 12QuadratureDegree3 min
- 13Differential equationsGraduate4 min
- 14Speed: BLAS, LAPACK and mixed precisionIndustry3 min
- 15Frontier: randomized and low-precision numericsResearch2 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Ten algorithms of the centuryDegree1 min
In the year 2000 a journal asked two numerical analysts to name the ten algorithms that had done most to shape science and engineering in the twentieth century. Their list runs from the Monte Carlo method, born at Los Alamos in 1946, through the simplex method, Krylov iterations, matrix decompositions, the first optimizing compiler, the QR algorithm, Quicksort, the fast Fourier transform, integer relation detection and the fast multipole method. Eight of the ten compute with real numbers. This part is about them, and about the question that hangs over every one: when every operation rounds, which answers can we trust?
Here is the question in miniature. Two equations in two unknowns. The answer is almost exactly one and one. Gaussian elimination, done the way it is taught in school, in double precision, answers that the first unknown is zero. Every digit is wrong. Swap the two equations before eliminating, and the same arithmetic gets it right. Nothing about the problem is difficult. A tiny change in the data changes the answer only a little. The algorithm was the problem. Separating the difficulty of a problem from the quality of an algorithm is the first idea of numerical analysis, and the rest of the part is built on it.
1Conditioning and stabilityDegree4 min
Before asking whether an algorithm is good, ask whether the problem is hard. Nudge the data x by a small relative amount. The answer moves too, and the ratio of the two relative changes is the problem's condition number, kappa. Write the change in f as f at x plus delta x, minus f at x, and regroup: a difference quotient, times x over f of x. As the nudge shrinks, the quotient becomes the derivative. Kappa is the size of x times f prime of x, over f of x. Notice what is missing: no algorithm, no rounding. Kappa belongs to the problem alone, and a problem with a large kappa is called ill conditioned.
Four small problems show the range. Subtracting one from a number very close to one: kappa is x over x minus one, about a million. That is Part 4's cancellation, and now we see it is the problem's fault, not the computer's. The square root has kappa one half everywhere: it halves relative errors. The exponential has kappa equal to x, so at x equal to one hundred, kappa is a hundred. The tangent, close to a right angle, has kappa about sixteen thousand. The rule of thumb: from data good to sixteen digits, expect about sixteen, minus the logarithm of kappa to base ten.
For a linear system A x equals b, perturb the right-hand side. Subtract the two equations: A times delta x equals delta b. So delta x is A inverse times delta b, and its size is at most the norm of A inverse times the size of delta b. Since b is A x, x is at least as large as b over the norm of A. Divide: the relative change in x is at most the norm of A, times the norm of A inverse, times the relative change in b. That product is the matrix's condition number, a name Alan Turing gave it in 1948. Geometrically, A turns the unit circle into an ellipse, and kappa is its longest axis over its shortest.
Some problems are ill conditioned through and through. David Hilbert's matrix has entries one over i plus j minus one. It arises when fitting polynomials by least squares, and its neighbouring columns are so nearly parallel that the system barely determines x. Our instrument measures its condition number: about sixteen thousand for size four, fifteen billion for size eight, and for size twelve, one point six times ten to the sixteen, past one over machine epsilon. By the rule of thumb, twelve digits survive at size four, six at size eight, and none at size twelve, whatever algorithm we use.
Conditioning is the problem's share of the error. Stability is the algorithm's. The exact map f takes data x to the answer f of x. The algorithm, f tilde, rounds at every step and lands somewhere else. James Wilkinson's question was: is there nearby data, x tilde, for which that wrong answer is exactly right? If there always is, within a small multiple of machine epsilon, the algorithm is called backward stable. A backward stable algorithm commits no more error than rounding the data once would, and conditioning turns that into the answer's error. The hook's two equations were well conditioned; elimination without row swaps was simply unstable.
2Backward error analysisGraduate2 min
James Wilkinson learned his trade beside Turing at the National Physical Laboratory, and he analysed rounding with one simple model. Every floating-point operation returns the exact result times one plus delta, where delta is at most the unit roundoff, about ten to the minus sixteen in double precision. Add three numbers. Each addition rounds once. Multiply it out, and each input picks up its own small factor. So the computed sum is the exact sum of slightly different numbers, each changed by about two roundings. That is a backward error: not how wrong the answer is, but how far the data must move to make it exactly right.
Why ask the question backwards? Because the two errors are tied together by the condition number. Suppose the computed answer, y hat, is the exact answer for data x plus delta x. To first order, the answer moves by f prime of x times delta x. Divide by y, and multiply and divide by x: the relative forward error is kappa times the relative backward error. Forward error is at most the condition number times the backward error. The algorithm controls one factor and the problem the other, and each can be studied on its own.
For linear systems the rule is exact, and the backward error can be measured. Given a computed solution x hat, form the residual: b minus A x hat. Add to A the rank-one matrix r times x hat transposed, over the size of x hat squared, and x hat solves the changed system exactly. That change, relative to A, has size the norm of r over the norm of A times the norm of x hat. Call it eta: it is computed after the fact, from things we have. Meanwhile the true error, x minus x hat, is A inverse times r. Take norms, and the relative error is at most kappa times eta, with no approximation at all.
3Gaussian eliminationDegree3 min
Elimination is the oldest algorithm in this part: the Chinese Nine Chapters on the Mathematical Art already use it. To clear the first column below the pivot, subtract two times row one from row two, and four times row one from row three. Then three times the new row two from row three. What remains is upper triangular: call it U. Keep the multipliers, two, four and three, in a lower triangular matrix with ones on its diagonal: call it L. Then A equals L times U, as Turing pointed out in 1948. Solving A x equals b is then two triangular solves: L from the top down, then U from the bottom up.
How much work is it? Step k updates the block below and to the right of the pivot: n minus k squared entries, each one multiply and one subtract. Add up the steps, and count from the end. The sum of the first squares is a cubic, and its leading term gives two thirds of n cubed operations. The triangular solves cost only about n squared each, so the factorization is done once and reused for every right-hand side. Computing the inverse instead would cost three times as much, hence the rule: to solve, never invert.
Here is the hook's failure. Eliminating with the tiny pivot epsilon needs the multiplier one over epsilon, and leaves one minus one over epsilon in the corner. With epsilon ten to the minus twenty, that rounds to minus ten to the twenty. The one is gone. The computed factors are the exact factors of a different matrix, with a zero where the one was. The cure is partial pivoting: before each step, swap up the row with the largest entry in the column, so every multiplier is at most one. In our instrument's runs, without pivoting the error grows as epsilon shrinks, until no digit is right; with pivoting it stays at the level of rounding.
With pivoting, how large can the entries of U become? Each step replaces an entry by itself minus a multiplier, at most one, times another entry, so the largest entry at most doubles. Over n minus one steps, the growth factor rho is at most two to the n minus one, as Wilkinson proved, and elimination's backward error grows with rho. The bound is attained: here the last column doubles at every step. Measured, it is exactly two to the n minus one on Wilkinson's matrix, nine times ten to the eighteen at size sixty-four, but about four for random matrices of that size. Lloyd Trefethen and Robert Schreiber studied this in 1990: in practice growth is small, and nobody has proved why.
4Least squares and QRGraduate3 min
Least squares, published by Adrien-Marie Legendre in 1805 and claimed by Gauss, fits a model with more equations than unknowns. We want the x that brings A x as close as possible to b. The closest A x is the foot of the perpendicular from b to the plane spanned by A's columns, so the residual is orthogonal to every column: A transposed times the residual is zero. Rearranged, these are the normal equations, a small square system. But A transposed A has the squares of A's singular values, so its condition number is kappa squared. A problem with kappa a million becomes one with kappa a trillion.
Gene Golub's answer, in 1965, was never to form A transposed A at all. Factor A as an orthogonal matrix Q times an upper triangular R. Multiplying by Q transposed changes no lengths, so the size of the residual is unchanged, and the problem splits in two. The bottom rows are what no x can fix; the top rows are a triangular system whose condition number is kappa, not kappa squared. Our instrument fits a tall system at four condition numbers. The normal equations' error grows like kappa squared, reaching thirty-seven percent at kappa ten to the eight. The QR solution's error grows only like kappa.
How do we find Q and R stably? Alston Householder's answer, in 1958, was mirrors. Take the first column, x, here three and four. We want a reflection that lays it on the first axis. Reflections keep lengths, so it must land at plus or minus five. The mirror is perpendicular to v, which points along x plus five times e one. Reflecting subtracts twice the component along v, and x lands exactly at minus five, zero. Choosing the sign this way adds two positive numbers instead of subtracting nearly equal ones: chapter one's cancellation, avoided. The same mirror carries the second column to minus three, one, and the matrix is triangular. A bigger matrix needs one mirror per column, each zeroing everything below the diagonal, and Q is their product.
The textbook way to get Q is Gram–Schmidt: take each column and subtract its components along the columns before it. Classical Gram–Schmidt measures each component against the original column. Modified Gram–Schmidt measures it against the column as updated so far. In exact arithmetic they are the same algorithm. In floating point, on Hilbert matrices, the classical version's Q is not orthogonal at all by size eight. The modified one loses orthogonality in proportion to kappa, as Åke Björck proved in 1967. Householder's mirrors stay orthogonal to machine precision at every size, because every mirror is exactly orthogonal by construction.
5The SVDGraduate3 min
The singular value decomposition. Every matrix, of any shape, has a singular value decomposition. Watch this two by two matrix act on the unit circle. First a rotation, V transposed, turns two special perpendicular directions onto the axes. Then a diagonal matrix, sigma, stretches each axis by a singular value. Then a second rotation, U, and the circle is an ellipse. In symbols, A sends each right singular vector v i to sigma i times u i. Side by side as columns, and since V is orthogonal, A equals U sigma V transposed. The longest stretch over the shortest is chapter one's condition number.
Multiply the decomposition out and a matrix becomes a sum of rank-one pieces, largest first. Keep the first k, and you have the best rank k approximation there is: Carl Eckart and Gale Young proved in 1936 that its error is the next singular value, the fact behind the embeddings of AI, Built, Part 3. Here are the eighty singular values of a matrix that blurs a signal. Below the rounding level they are noise in the arithmetic, so the numerical rank is 56, not eighty. And below the noise in our data, one part in a thousand, only 25 carry information. In floating point, rank depends on a tolerance.
Here is the experiment. A signal of two boxes, in green, is blurred by that matrix, and noise of one part in a thousand is added: the yellow curve. Can we undo the blur? Invert each factor of the decomposition, and the solution is a sum with one term per singular value, each coefficient divided by its sigma. But the noise is divided by the singular values too, and the smallest is ten to the minus sixteen. The condition number is about ten to the sixteen, and the naive solution's error is ten to the thirteen times the signal. The arithmetic is not at fault: the problem, as posed, cannot be solved.
The cure is to stop dividing by tiny numbers. Keep only the first k terms: the truncated SVD. Each term dropped loses a little signal; each term kept adds noise divided by its sigma. Our instrument tries every k. The error falls from 77 percent with one term to 19 percent at k equals 23, then explodes, back to ten to the thirteen with all eighty. At the best k the two boxes come back, a little rounded. Andrey Tikhonov's regularization, from 1963, damps each term smoothly instead of cutting it off. Either way, we deliberately solve a nearby, well-conditioned problem.
6Eigenvalues: the QR algorithmGraduate3 min
An eigenvector is a direction that a matrix only stretches: A v equals lambda v. Move everything to one side. A minus lambda I sends v to zero, so it is singular, and its determinant vanishes. That determinant is a polynomial of degree n, and the eigenvalues are its roots: here, the eight roots for a random symmetric eight by eight matrix. Niels Henrik Abel proved in 1824 that no formula in radicals solves the general polynomial of degree five. And every polynomial is the characteristic polynomial of some matrix, its companion matrix. So no finite recipe finds eigenvalues in general: every eigenvalue algorithm must iterate.
In 1961 John Francis in England and, independently, Vera Kublanovskaya in the Soviet Union found the algorithm still used today. Factor the matrix as Q times R. Since Q is orthogonal, R is Q transposed A. Now multiply the factors in the other order. The result is Q transposed A Q, a similarity, so the eigenvalues are unchanged: it is the power method applied to a whole basis at once. Repeat, and the matrix creeps towards diagonal form, the eigenvalues appearing on its diagonal. Coloured by size on a log scale, our matrix's last off-diagonal entry fades to ten to the minus fifteen in forty iterations. Finishing all eight takes 623.
Three refinements make it fast. First, reduce the matrix once, with Householder mirrors on both sides, to Hessenberg form, zero below the first subdiagonal; a symmetric matrix becomes tridiagonal. The QR algorithm keeps this shape, and each step then costs n squared with Givens rotations, not n cubed. Second, shift: subtract a guess at an eigenvalue before factoring, and add it back after. James Wilkinson's shift is an eigenvalue of the bottom two by two block. Third, deflate: when the last subdiagonal entry is negligible, the bottom eigenvalue is found, and the iteration carries on with a smaller matrix. With all three, our eight eigenvalues take 16 iterations instead of 623.
Here is why the shift matters. Without it, the last subdiagonal entry shrinks by a constant factor each step: a straight line on a log scale, linear convergence. With Wilkinson's shift it goes from eight times ten to the minus four, to four times ten to the minus twelve, to three times ten to the minus thirty-five. The number of correct digits roughly triples each time; the measured orders are about three point seven and three. That is cubic convergence, and Wilkinson proved in 1968 that, with his shift, the symmetric iteration always converges. The answers agree with LAPACK's to about ten to the minus fourteen. Nearly every eigenvalue you have ever been shown was computed this way.
7Conjugate gradientsGraduate3 min
For a symmetric positive definite matrix, solving A x equals b is the same as going downhill. Define phi of x as a half x transposed A x, minus b transposed x. It is a bowl, and these ellipses are its contours. Its gradient is A x minus b: zero exactly at the solution, and minus the residual everywhere else. So Part 23's gradient descent applies. Step along the residual for as long as the bowl keeps falling, and repeat. In a long, narrow bowl it zigzags, each step undoing part of the last. Conjugate gradients, on the same bowl, arrives in two steps.
Why two steps? The conjugate gradient method of Magnus Hestenes and Eduard Stiefel, from 1952, does more than go downhill. After k steps, the only vectors it can have built from b are combinations of b, A b, A squared b, and so on: the Krylov space. Conjugate gradients picks the best point in that whole space, in the bowl's own norm, not just the best along one line. It can, because its search directions are conjugate, orthogonal in A's inner product, so a new step never spoils the old ones. The loop is short: one product with A, two inner products, four vectors of memory. In exact arithmetic it ends within n steps; in practice, far sooner.
How fast is it? The error falls at least as fast as twice a ratio to the power k: root kappa minus one, over root kappa plus one. For large kappa that ratio is about one minus two over root kappa, so the number of steps grows like the square root of the condition number. Steepest descent has kappa where conjugate gradients has its square root. Our instrument solves the Poisson problem, chapter eight's matrix, on three grids; kappa grows with the number of unknowns. Steepest descent needs 897 steps on the smallest grid and 3,297 on the next, and on the largest grid had not converged after eight thousand. Conjugate gradients needs 52, 101 and 198, about half of what the bound allows.
Since the cost depends on kappa, change kappa. Multiply the system by the inverse of a matrix M that resembles A but is cheap to solve with. The solution is unchanged, and if M is a good imitation, M inverse A has a much smaller condition number. The simplest choice, A's own diagonal, does nothing here: the Poisson matrix has fours all along its diagonal, and the step counts are identical. Symmetric successive over-relaxation, two triangular sweeps, cuts 101 steps to 26, and 198 to 47. Incomplete Cholesky factors do better still, and chapter nine's multigrid can make the count independent of the grid.
8Sparse matricesIndustry3 min
The matrices of chapters seven and nine come from equations like Poisson's, which governs steady heat, electric potential and pressure. We want u on a square, given f, with u zero on the edge. Sample u on a grid with spacing h. Adding the Taylor series of u at x plus h and at x minus h cancels the odd terms, so the second derivative becomes a second difference, divided by h squared. Do the same in y and add: each grid point is coupled to its four neighbours, four times itself minus each neighbour once. That is one equation per grid point, with at most five unknowns in each.
Direct solvers factor the matrix, and there sparsity is fragile. In this arrow matrix one unknown, the hub, is coupled to all the others. Seymour Parter's view of elimination, from 1961, is a graph: eliminating an unknown couples all of its neighbours to one another. Eliminate the hub first and every pair of the others becomes coupled: the factor fills in completely. Eliminate it last, and nothing fills in at all. Same matrix, same answer; only the order differs. On the sixty-four by sixty-four grid, numbered row by row, the Cholesky factor has two hundred and sixty-two thousand nonzeros, 13 times as many as the matrix.
So the order of elimination is the whole game. Numbered row by row, the grid is eliminated like a broom sweeping a floor, and the front of partly eliminated unknowns couples everything behind it to everything ahead: a band of width m fills completely. Minimum degree, a greedy rule that goes back to Harry Markowitz in 1957, always eliminates the unknown with the fewest neighbours next. Nested dissection, Alan George's idea of 1973, cuts the grid in two with a line of unknowns, numbers the line last, and does the same to each half. On a two-dimensional grid its fill grows like n log n and its work like n to the three halves, which is the best possible order of growth.
Here is what the orderings buy on our grid of four thousand and ninety-six unknowns. Row by row, the factor has two hundred and sixty-two thousand nonzeros. Reverse Cuthill–McKee, which only narrows the band, a hundred and eighty-one thousand. Minimum degree, sixty-three thousand, about three times the matrix itself; our simple nested dissection, eighty-nine thousand. Nested dissection's advantages are growth and parallelism: its halves are independent, which is why libraries such as METIS use it on large meshes. When the grid side doubles, row-by-row fill grows eightfold, the good orderings' less than sixfold. In three dimensions the separators are planes, fill grows like n to the four thirds, and iterative methods take over.
9MultigridGraduate4 min
Go back to Poisson's equation, in one dimension to start: sixty-three unknowns, two on the diagonal and minus one beside it. The simplest iteration, weighted Jacobi, moves each unknown part of the way towards the value its own equation wants. Subtract the true solution and b cancels: the error is multiplied by the same matrix at every sweep. That matrix shares its eigenvectors with A, and they are sine waves: mode one is a single smooth hump, mode sixty-three a zigzag. So each sweep simply scales each mode, by a factor we can write down. Moving two thirds of the way, the rough upper half of the modes shrinks by at least a factor of three per sweep. The smoothest mode keeps nought point nine nine nine of itself.
Watch it happen. These bars are a random error, measured along each of the sixty-three sine waves: smooth modes on the left, rough ones on the right. One sweep, and the right half drops. Three sweeps. After ten, the rough half has all but vanished, and the smoothest mode has lost less than one percent. So relaxation on its own is hopeless: the error that remains is smooth, and smooth error barely moves. But relaxation does one thing superbly. It smooths.
Here is the trick. A smooth wave on a fine grid of fifteen points, mode six, sits in the lower half of the spectrum, where relaxation is slow. Keep every other point. On the coarse grid of seven, the same wave is mode six of seven: in the upper half, where relaxation is fast. So relax a few times, compute the residual, and carry it down to the coarse grid. Solve there for the correction, interpolate it back, add it, and relax again. Radii Fedorenko published this two-grid scheme in 1964, and Achi Brandt made it practical in the 1970s. The coarse problem is the same kind of problem, so treat it the same way.
Recursing gives the V-cycle. Relax and restrict, down through coarser and coarser grids to one of a few points; solve that exactly; then interpolate and relax on the way back up. Our instrument runs it on the two-dimensional Poisson problem. On a grid of two hundred and twenty-five unknowns, each cycle cuts the residual by a factor of about five. On nine hundred and sixty-one unknowns, the same. On sixteen thousand, the same. The curves lie on top of one another, and ten cycles reach a few parts in a hundred million on every grid. The number of cycles does not grow with the problem.
And each cycle is cheap. It relaxes on the finest grid, work proportional to n, and then does the same on a grid with a quarter of the points. Unroll that: n, times one plus a quarter plus a sixteenth and so on, which is four thirds of the work on the finest grid alone. Now compare the ways of solving the same Poisson problem. Dense elimination grows like n cubed; the band, row by row, like n squared; nested dissection, and conjugate gradients, like n to the three halves. Multigrid grows like n. That is the cost of reading the right-hand side, so no method can do better. For unstructured problems, algebraic multigrid builds its coarse levels from the matrix itself, and is often the preconditioner inside conjugate gradients.
10Roots and Newton's fractalDegree3 min
Every method in this chapter hunts for a zero, and our test case is the square root of two, the positive root of x squared minus two. Bisection needs only a sign change. f is negative at one and positive at two, so a root lies between them. Evaluate the midpoint, keep the half that still changes sign, and repeat. The bracket halves every time, so each step gains one bit, about three tenths of a decimal digit. Bisection cannot fail, and it is slow: after forty steps, twelve digits.
Newton's method uses the slope as well. Near x, f of x plus h is about f of x plus f prime of x times h: the tangent line. Set that to zero, solve for h, and step. From two, the tangent lands at one and a half, and the next at one point four one six seven. Keep one more term of Taylor's series, and the new error is a constant times the old error squared. An error of a thousandth becomes about a millionth: the correct digits double at every step. The secant method replaces the derivative by the slope through the last two points. Its order is the golden ratio, one point six one eight.
Here is the race, computed. Bisection climbs its straight line, three tenths of a digit per step. The secant method's correct digits go one, two, three, six, nine and a half, then nearly sixteen, the limit of double precision. Newton's go one, two and a half, five and a half, twelve, sixteen: doubling. But each Newton step evaluates both f and its derivative. Counted per evaluation, Newton's order is the square root of two, and the secant method, at one point six one eight, is the faster of the two.
Newton's method works for complex numbers too, and in 1879 Arthur Cayley asked which root it finds from a given start. For z squared minus one the answer is simple: the nearer root. For z cubed minus one, colour every starting point by the root it reaches, darker where it takes longer. Each root sits in a calm basin of its own colour. But the boundary between basins is not a line. Wherever two colours meet, the third appears between them, in smaller and smaller copies.
Zoom in. A window fifteen times smaller, on the boundary: the same structure, buds on buds. In the exact picture it never ends, because every point on the boundary of one basin is on the boundary of all three. Zoom twenty times further, but into the interior of a basin, and the picture goes flat: every start there reaches the same root in six steps. Fast near a root, unpredictable far from one: that is why the root finders in libraries are safeguarded. Brent's method, from 1973, keeps a bisection bracket and takes fast interpolation steps only while they stay inside it.
11ApproximationGraduate2 min
To stand in for a function, the obvious idea is to sample it and pass a polynomial through the samples. In 1901 Carl Runge tried it on a perfectly smooth function, one over one plus twenty-five x squared. Through eleven equally spaced points, the polynomial follows it in the middle but swings near the ends. Through twenty-one points it is far worse: near the ends the error is about sixty. With eighty-one points it is six times ten to the fourteen. More data gives a worse answer. The function is innocent: the points are to blame.
The cure is to choose the points. Space points evenly around a semicircle and drop them onto the diameter. These are Chebyshev points, crowded towards the ends. Why there? The interpolation error is a derivative of f, which we cannot change, times the node polynomial, the product of x minus each sample point, which we can. For equally spaced points it is small in the middle and nearly a hundred times larger near the ends. For Chebyshev points it ripples evenly and never exceeds two to the one minus n, within a factor of two of the smallest maximum any choice of points can have.
Here is the difference, computed. Through twenty-one Chebyshev points, the polynomial is already within two hundredths of Runge's function everywhere. As the degree grows, the equispaced error explodes, and the Chebyshev error falls geometrically, to about one ten-millionth at degree eighty. The rate is set by where f stops being smooth: poles at plus and minus i over five, off the real line. The ellipse around the interval that passes through them has a parameter rho, one plus root twenty-six, over five, about one point two two, and the error falls like rho to the minus n: the dashed line.
12QuadratureDegree3 min
To integrate, sample the function and add up. Our test integral is e to the x times cosine three x, from nought to two. Its exact value is about minus one hundredth: a small difference of large areas. The trapezoid rule joins the samples with straight lines. Its error shrinks like h squared: halve the spacing and the error falls fourfold. Combine two trapezoid sums, four times the finer one minus the coarser, over three, and the h squared terms cancel. That is Simpson's rule, and its error falls like h to the fourth.
Both rules fix the sample points and choose only the weights. In 1814 Carl Friedrich Gauss chose the points too. With two points there are four unknowns, two nodes and two weights, so we may demand the right answer for one, x, x squared and x cubed. Solving gives weights of one at plus and minus one over root three: two samples, exact for every cubic. With n points the rule is exact up to degree two n minus one. The nodes are the roots of Legendre polynomials, crowded towards the ends like chapter eleven's Chebyshev points. Gene Golub and John Welsch showed in 1969 that they are the eigenvalues of a symmetric tridiagonal matrix, so chapter six's QR algorithm computes them.
Here are four rules on our integral, computed. The trapezoid error falls fourfold each time the points double, to about a thousandth at sixty-four intervals. Simpson's falls sixteenfold, to about a millionth. Gauss reaches four times ten to the minus fifteen with just sixteen points, and then can go no further: that is rounding. For a smooth integrand its error falls geometrically, like Chebyshev interpolation. Monte Carlo, the average of f at random points, is worst by far: with sixty-five samples its typical error is still more than a half.
Monte Carlo loses in one dimension, and wins in many. An integral is an average, so estimate it by averaging f at N random points: the first algorithm on this part's list of ten, from Los Alamos. The variance of an average of N independent samples is the variance of one sample over N, so the error falls like one over root N, whatever the dimension. A grid with N points in d dimensions has spacing N to the minus one over d, and the trapezoid error falls like N to the minus two over d. Above four dimensions, Monte Carlo wins, and in the hundreds of dimensions of finance and physics nothing else is feasible.
13Differential equationsGraduate4 min
A differential equation gives the slope of its solution everywhere, and a solver walks along it. By Taylor's series, the value a step h later is the value now, plus h times the slope, plus a term of order h squared. Dropping the rest is Euler's method: on y prime equals y, four steps of a half reach five, not seven point three nine. Carl Runge and Wilhelm Kutta sampled the slope four times per step, so that the errors cancel up to h to the fourth. The same four steps reach seven point three eight.
How large a step? Let the method decide. The formulas of John Dormand and Peter Prince, from 1980, give two answers from the same seven slopes, of fifth and fourth order. Their difference estimates the error, which grows like h to the fifth. Ask for the next step's error to equal the tolerance. Divide, and the constant cancels: scale h by the fifth root of tolerance over error. Add a safety factor, and retry any step that fails. That is our instrument's loop, and the method behind SciPy's default solver and MATLAB's ode45.
Now a harder kind of equation. Its solution is cosine t minus e to the lambda t: for large negative lambda, a brief transient, then just the smooth cosine. With lambda minus one, the adaptive method takes eleven steps; with minus a hundred, a hundred and thirty-two. With minus ten thousand, six thousand and sixty-seven, though after the first instant the answer is the same gentle cosine. Backward Euler takes two hundred steps every time, and its error even shrinks. This is stiffness: a decay that is already over still dictates an explicit method's step.
Why? Test each method on y prime equals lambda y, with z equal to h times lambda: each step multiplies y by some R of z. Euler's factor is one plus z: stable only in a disc around minus one. Runge–Kutta four's is its Taylor polynomial: a larger region, but still bounded. Backward Euler takes the slope at the new point, which gives one over one minus z, smaller than one in the whole left half-plane. Germund Dahlquist named this A-stability in 1963. An explicit method's factor is a polynomial, unbounded, so no explicit method is A-stable.
Some problems care less about one moment than about what is conserved over millions of steps: planets, molecules, particle beams. Leapfrog, which Loup Verlet used for molecules in 1967, gives the momentum half a kick, lets the position drift a full step, then finishes the kick. Each part is a shear of phase space, which keeps areas exactly: the step is symplectic. We ran an orbit of eccentricity one half for a thousand revolutions, a hundred steps each. Runge–Kutta four's orbit has shrunk. Leapfrog's has the right size, but has turned.
Here is the energy after every orbit. Runge–Kutta four starts out more accurate, but its error grows steadily, to three percent after a thousand orbits. Leapfrog's is about one percent, and never grows. After about three hundred and seventy orbits leapfrog is ahead, and the gap only widens. The reason is a theorem: a symplectic method almost exactly conserves a slightly different energy, a modified Hamiltonian, so the true energy can only wobble around it. It is chapter two's backward error analysis again: the method solves a nearby problem, nearly exactly.
14Speed: BLAS, LAPACK and mixed precisionIndustry3 min
Almost every algorithm in this part spends its time in a few kernels, standardized as the Basic Linear Algebra Subprograms, the BLAS. Level one, from 1979, works on vectors: a times x plus y does two operations per element and moves twenty-four bytes, one twelfth of an operation per byte. Level two, from 1988, multiplies a matrix by a vector, and uses each matrix entry once: a quarter per byte. Level three, from 1990, multiplies matrices: two n cubed operations on three n squared numbers, an intensity of n over twelve, growing with n. That is Part 9's roofline in one line: only level three does enough arithmetic per byte to keep a processor busy.
Here are the three levels timed on this machine, through NumPy, which calls an optimized BLAS. Matrix multiplication climbs as n grows, to about 289 billion operations per second at two thousand and forty-eight. The other two, at that size, manage 0.7 and 27 billion: 408 and 11 times slower, doing the same kind of arithmetic. Small vector additions fit in cache and run faster than large ones, which is Part 9's memory hierarchy, not arithmetic. So the craft of numerical linear algebra since 1990 has been to recast every algorithm so that most of its work is level three.
LAPACK, released in 1992, does exactly that. Take chapter three's elimination, but instead of one column at a time, factor a narrow panel of b columns, then update everything to its lower right at once: the trailing matrix minus a product of two thin blocks, a matrix multiplication. Move to the next panel. Only the panels run at level two, about n squared b over two operations out of two thirds n cubed, a fraction of three b over four n. For ten thousand unknowns and panels of sixty-four, half of one percent. When NumPy solves a linear system, it calls exactly this routine.
Speed also comes from fewer bits: single precision moves half the bytes, and usually runs at least twice as fast. So factor the matrix once in single precision: that is the n cubed work. Compute the residual in double, which costs only n squared, solve for a correction with the cheap factors, and add it. Each round multiplies the error by about kappa times single precision's rounding unit, so it converges when that product is below one. With kappa ten to the five, our instrument gains nearly three digits a round, and after four rounds is about as accurate as a full double-precision solve. Chapter fifteen goes down to sixteen bits.
15Frontier: randomized and low-precision numericsResearch2 min
Can randomness, and fewer bits, make linear algebra faster and still right? The first frontier is randomness. To approximate a large matrix by one of rank 20, multiply it by a thin random matrix. The product's columns are random mixtures of the matrix's own columns, and with high probability they span almost exactly its most important directions. Orthonormalize them, project, and take the SVD of a small matrix. Nathan Halko, Per-Gunnar Martinsson and Joel Tropp analysed this in 2011. On our 1,200 by 600 matrix, a few extra random columns and one or two power steps bring the error to within 1 percent of the best any rank-20 matrix can do, in a fraction of the 69.1 seconds a full SVD takes.
The second frontier is precision. Graphics processors do arithmetic in sixteen bits many times faster than in sixty-four, because machine learning wants them to. Can numerical linear algebra use those bits without losing accuracy? Iterative refinement, an idea of Wilkinson's, says yes, sometimes. Factor the matrix cheaply in low precision, compute the residual in high precision, and solve for a correction using the cheap factors. For a well-conditioned matrix the error falls to double precision in two or three steps. For condition number ten to the eight, times single precision's epsilon of about ten to the minus seven, the product exceeds one, and refinement diverges. Since 2019 a benchmark built on this idea runs beside the classic Linpack ranking of supercomputers.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. The condition number, which says how hard a problem is, separate from backward stability, which says how good an algorithm is, and the rule that joins them: forward error is at most the condition number times the backward error. Elimination made stable by pivoting; Householder's mirrors and the SVD; the QR algorithm, converging cubically; conjugate gradients, multigrid and sparse orderings for systems with millions of unknowns; Newton's method and its fractal; Chebyshev points, Gauss quadrature, stiff solvers and symplectic integrators. One idea runs through it: with rounding everywhere, the right question is not whether an answer is exact, but whether it is the exact answer to a nearby problem.
Where this comes back. Part 51's renderer is linear algebra and integration, done billions of times a second. Part 53's quantum computer is a unitary matrix acting on a vector. Part 54 proves programs correct, floating point included. Part 56 reads a graph through the eigenvalues of its matrix. And Part 57's learning theory rests on the same optimization.
In practice. Never invert a matrix to solve a system: factor it, with pivoting. Fit least squares with QR or the SVD, not the normal equations. Estimate the condition number and report residuals, not only answers. Use sparse and iterative methods, with a good preconditioner, for big systems. And call BLAS and LAPACK: write your own matrix multiplication only to learn how it works.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: a two-grid solver for the one-dimensional Poisson problem, whose convergence factor should not depend on the size of the grid. The last, marked with a star, is a research problem: prove that partial pivoting's growth is polynomial once the matrix is perturbed by a little noise.
Next time, Part 53: quantum computation. A qubit is a unit vector in a two-dimensional complex space, a gate is a unitary matrix, and a computation is a product of them, linear algebra again. Interference makes wrong answers cancel, and one algorithm built on it, Shor's, would end the public-key cryptography of Part 30.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 53's quantum computer is a unitary matrix acting on a vector. Part 54 proves programs correct, floating point included. Part 56 reads a graph through the eigenvalues of its matrix, and Part 57's learning theory rests on the same optimization. Part 51's renderer is this part's linear algebra and integration done billions of times a second.
Key results
The part's results in one place, for revision.
Try it
Lab 52 · Which answers to trust: backward error, pivoting, and two fast solvers
Solve Hilbert systems and compare the forward error with kappa times the backward error, break elimination with a tiny pivot and with Wilkinson's matrix, check conjugate gradients against its bound at every step, and measure multigrid's convergence factor on three grids.
python -m videos.cs.labs 52
needs numpy, scipy, matplotlib · download lab52.py ·
source on GitHubHilbert system, n = 4: kappa 1.6e+04 backward error 6.1e-17 forward error 2.0e-13 kappa x (backward + eps) 4.4e-12
Hilbert system, n = 8: kappa 1.5e+10 backward error 3.2e-17 forward error 5.2e-08 kappa x (backward + eps) 3.9e-06
Hilbert system, n = 12: kappa 1.6e+16 backward error 3.4e-17 forward error 5.5e-02 kappa x (backward + eps) 4.1e+00
[[1e-20, 1], [1, 1]] x = (1, 2) error without pivoting 1.00, with partial pivoting 0.0e+00
growth factor at n = 48 Wilkinson's matrix 1.41e+14 = 2^47; 12 random matrices: mean 3.7, largest 5.2
Poisson, 256 unknowns, kappa 116: steps to 1e-8 steepest descent 912, conjugate gradients 52; A-norm error after 30 steps 7.3e-04, bound 7.6e-03
multigrid V-cycle, residual factor per cycle 225 unknowns: 0.19, 961 unknowns: 0.20, 3,969 unknowns: 0.20
A backward error near rounding level on every Hilbert system says the solver is stable; the lost digits belong to the problem. CG's steps grow like the square root of kappa, and multigrid's do not grow at all.
The code (101 lines; it asserts its own result)
"""Lab 52: separate conditioning from stability on four solvers: elimination, least squares, conjugate gradients, multigrid."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import math
import numpy as np
import scipy.sparse.linalg as spla
from explainer.cs.numeric import iterative, linalg
TITLE = "Which answers to trust: backward error, pivoting, and two fast solvers"
GOAL = ("Solve Hilbert systems and compare the forward error with kappa times the backward error, break elimination "
"with a tiny pivot and with Wilkinson's matrix, check conjugate gradients against its bound at every step, "
"and measure multigrid's convergence factor on three grids.")
TASKS = [
"Call linalg.least_squares() and plot both errors against kappa on log axes. Which method's error grows like kappa and which like kappa squared, and where do the normal equations lose every digit?",
"Pass M=iterative.ssor(A, 1.5) to iterative.cg. How many steps does it save on the 32 x 32 grid, and what condition number would explain that through the bound?",
"Add 1e-8 times a Gaussian matrix to linalg.wilkinson_matrix(32) and factor it with linalg.lu. What happens to the growth factor of 2^31, and what does that say about worst cases in practice?",
]
def a_norm(A, e):
return float(np.sqrt(e @ (A @ e)))
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. forward error <= kappa x backward error: the algorithm is stable, the problem is not
rows = linalg.forward_vs_backward(seed=seed)
eps = np.finfo(float).eps
for r in rows:
r["bound"] = r["kappa"] * (r["backward"] + eps) # eps: the right-hand side b = Hx was itself rounded
assert r["backward"] < 4e-16, "pivoted elimination is backward stable on every size"
assert r["forward"] <= r["bound"], "forward error is at most kappa times the backward error"
assert rows[-1]["forward"] > 1e6 * rows[0]["forward"], "the forward error grows with the condition number"
for r in (rows[0], rows[2], rows[-1]):
lab.row(f"Hilbert system, n = {r['n']}: kappa {r['kappa']:.1e}",
f"backward error {r['backward']:.1e} forward error {r['forward']:.1e} kappa x (backward + eps) {r['bound']:.1e}")
# 2. an unstable algorithm on a well-conditioned problem, and the worst case of the stable one
piv = linalg.pivot_failure()[-1] # eps = 1e-20
assert piv["err_no_pivot"] > 0.5 and piv["err_pivot"] < 1e-15
lab.row("[[1e-20, 1], [1, 1]] x = (1, 2)", f"error without pivoting {piv['err_no_pivot']:.2f}, with partial pivoting "
f"{piv['err_pivot']:.1e}")
sizes = (8, 16, 32, 48)
wilk = [float(linalg.lu(linalg.wilkinson_matrix(n))[3]) for n in sizes]
rand = [[float(linalg.lu(rng.standard_normal((n, n)))[3]) for _ in range(12)] for n in sizes]
assert wilk == [2.0 ** (n - 1) for n in sizes], "Wilkinson's matrix attains the bound 2^(n-1)"
assert max(max(r) for r in rand) < 30, "random matrices grow by a small factor"
lab.row("growth factor at n = 48", f"Wilkinson's matrix {wilk[-1]:.2e} = 2^47; 12 random matrices: mean "
f"{np.mean(rand[-1]):.1f}, largest {max(rand[-1]):.1f}")
# 3. conjugate gradients on the 16 x 16 Poisson problem against its bound, step by step
m = 16
A = iterative.poisson2d(m)
b = rng.standard_normal(m * m)
exact = spla.spsolve(A.tocsc(), b)
kappa = 1 / math.tan(math.pi / (2 * (m + 1))) ** 2 # lambda_max / lambda_min of the five-point Laplacian
rate = (math.sqrt(kappa) - 1) / (math.sqrt(kappa) + 1)
e0 = a_norm(A, exact)
ks = list(range(1, 46))
err = [a_norm(A, exact - iterative.cg(A, b, tol=0.0, max_iter=k)[0]) / e0 for k in ks]
bound = [2 * rate ** k for k in ks]
assert all(e <= bd * (1 + 1e-9) for e, bd in zip(err, bound)), "CG's error is under 2 ((sqrt k - 1)/(sqrt k + 1))^k"
_, h_cg = iterative.cg(A, b)
_, h_sd = iterative.steepest(A, b)
assert len(h_sd) > 8 * len(h_cg)
lab.row(f"Poisson, 256 unknowns, kappa {kappa:.0f}: steps to 1e-8", f"steepest descent {len(h_sd) - 1}, conjugate "
f"gradients {len(h_cg) - 1}; A-norm error after 30 steps {err[29]:.1e}, bound {bound[29]:.1e}")
# 4. multigrid: the same factor per cycle on every grid
mg = iterative.multigrid_experiment(ms=(15, 31, 63), cycles=8, seed=seed)
factors = [r["factor"] for r in mg]
assert max(factors) < 0.3 and max(factors) - min(factors) < 0.05, "the V-cycle's rate does not depend on the grid"
lab.row("multigrid V-cycle, residual factor per cycle", ", ".join(f"{r['n']:,} unknowns: {r['factor']:.2f}" for r in mg))
lab.note = ("A backward error near rounding level on every Hilbert system says the solver is stable; the lost "
"digits belong to the problem. CG's steps grow like the square root of kappa, and multigrid's do "
"not grow at all.")
fig, ax = labs.figure(2, size=(11, 4.3))
ns = [r["n"] for r in rows]
ax[0].semilogy(ns, [r["bound"] for r in rows], "o--", color=labs.MUTED, label="kappa x (backward error + eps)")
ax[0].semilogy(ns, [r["forward"] for r in rows], "o-", color=labs.RED, label="forward error")
ax[0].semilogy(ns, [max(r["backward"], 1e-18) for r in rows], "o-", color=labs.GREEN, label="backward error")
ax[0].set(title="Hilbert systems: a stable solver, an ill-conditioned problem", xlabel="matrix size n",
ylabel="relative error")
ax[0].legend()
ax[1].semilogy(ks, bound, color=labs.MUTED, ls="--", label="CG's bound")
ax[1].semilogy(ks, err, color=labs.GOLD, label="conjugate gradients, A-norm error")
ax[1].semilogy(range(len(h_sd[:46])), h_sd[:46], color=labs.ORANGE, label="steepest descent, residual")
for r, color in zip(mg, (labs.BLUE, labs.TEAL, labs.PURPLE)):
ax[1].semilogy(range(len(r["residuals"])), r["residuals"], "o-", ms=3, color=color,
label=f"multigrid, {r['n']:,} unknowns")
ax[1].set(title="Poisson's equation: error against steps or cycles", xlabel="step (CG, descent) or V-cycle",
ylabel="relative error or residual", ylim=(1e-9, 3))
ax[1].legend(fontsize=8)
lab.fig = fig
return lab
Now change it
- Call linalg.least_squares() and plot both errors against kappa on log axes. Which method's error grows like kappa and which like kappa squared, and where do the normal equations lose every digit?
- Pass M=iterative.ssor(A, 1.5) to iterative.cg. How many steps does it save on the 32 x 32 grid, and what condition number would explain that through the bound?
- Add 1e-8 times a Gaussian matrix to linalg.wilkinson_matrix(32) and factor it with linalg.lu. What happens to the growth factor of 2^31, and what does that say about worst cases in practice?
Problems, with solutions
Try each problem before opening its solution.
-
Cancellation. Show that the relative condition number of f(x) = x − 1 is |x|/|x − 1|, and explain catastrophic cancellation with it.
Solution
The relative condition number is κ(x) = |x f′(x)/f(x)|, and f′(x) = 1, so κ = |x|/|x − 1|. It is near 1 away from x = 1 and unbounded as x → 1: at x = 1.000001 it is 1,000,001. Rounding the data alone, x ↦ fl(x) with relative error at most u = 2⁻⁵³, therefore moves the answer by a relative amount up to κu ≈ 1.1 × 10⁻¹⁰. In double precision fl(1.000001) − 1 = 9.999999999177334 × 10⁻⁷, a relative error of 8.2 × 10⁻¹¹: about ten correct digits of sixteen. The subtraction itself is exact (Sterbenz: if y/2 ≤ x ≤ 2y then x − y is a floating-point number), so nothing went wrong in the arithmetic; the leading digits of x and 1 cancel, and what is left are the digits that rounding had already spoiled, promoted to leading position. Catastrophic cancellation is a large condition number, not a bad algorithm: in general κ(x − y) = (|x| + |y|)/|x − y| with respect to perturbations of x and y, large exactly when x ≈ y. The cure is to reformulate before subtracting (for example √(x + 1) − √x = 1/(√(x + 1) + √x)), not to subtract more carefully.
-
Growth. Prove that partial pivoting's growth factor is at most 2ⁿ⁻¹, and that Wilkinson's matrix attains it.
Solution
Let ρ = max over all stages k and all i, j of |a⁽ᵏ⁾ᵢⱼ|, divided by max |aᵢⱼ|. Partial pivoting brings the entry of largest magnitude in column k to the pivot position, so every multiplier satisfies |ℓᵢₖ| ≤ 1. Step k replaces a⁽ᵏ⁾ᵢⱼ by a⁽ᵏ⁺¹⁾ᵢⱼ = a⁽ᵏ⁾ᵢⱼ − ℓᵢₖa⁽ᵏ⁾ₖⱼ, so max |A⁽ᵏ⁺¹⁾| ≤ (1 + 1) max |A⁽ᵏ⁾|; after n − 1 steps, max |U| ≤ 2ⁿ⁻¹ max |A|. Wilkinson's matrix W has 1 on the diagonal, −1 below it, 1 in the last column and 0 elsewhere, so max |W| = 1. In column 1 every candidate has magnitude 1; with ties broken in favour of the row already in place (as
numpy.argmaxdoes in ourlu), no row is swapped and every multiplier is −1, so each lower row has row 1 added to it. That zeroes the subdiagonal of column 1, leaves the −1s of columns 2, …, n − 1 unchanged (row 1 is zero there), and doubles the last column below row 1 from 1 to 2. The trailing (n − 1) × (n − 1) block is again Wilkinson's matrix with its last column scaled by 2, so by induction the last column of U is 1, 2, 4, …, 2ⁿ⁻¹ and ρ = 2ⁿ⁻¹. Our instrument confirms it exactly: 8, 128, 32,768, 2,147,483,648 and 2⁶³ ≈ 9.2 × 10¹⁸ at n = 4, 8, 16, 32 and 64. -
Gram–Schmidt. Show that classical Gram–Schmidt and modified Gram–Schmidt are equal in exact arithmetic, and give a 3 × 3 example where they differ in floating point.
Solution
Classical Gram–Schmidt uses rᵢⱼ = qᵢᵀaⱼ; modified uses rᵢⱼ = qᵢᵀv⁽ⁱ⁾ with v⁽ⁱ⁾ = aⱼ − Σₗ₍ₗ₌₁…ᵢ₋₁₎ rₗⱼqₗ, the column as updated so far. By induction on i, if q₁, …, qᵢ are orthonormal then qᵢᵀv⁽ⁱ⁾ = qᵢᵀaⱼ − Σₗ rₗⱼ qᵢᵀqₗ = qᵢᵀaⱼ, since qᵢᵀqₗ = 0 for l < i. So the coefficients, the vectors v and the normalized qⱼ are identical, and orthonormality passes to the next column. In floating point the qₗ are only nearly orthogonal and the step qᵢᵀqₗ = 0 fails. Take ε = 10⁻⁸, so that 1 + ε² rounds to 1, and A = [[1, 1, 1], [ε, 0, 0], [0, ε, 0]] (columns a₁ = (1, ε, 0), a₂ = (1, 0, ε), a₃ = (1, 0, 0)). Both versions give q₁ = (1, ε, 0) (its norm rounds to 1) and q₂ = (0, −1, 1)/√2. For the third column, classical Gram–Schmidt computes q₁ᵀa₃ = 1 and q₂ᵀa₃ = 0, so v = (0, −ε, 0) and q₃ = (0, −1, 0): q₂ᵀq₃ = 1/√2 ≈ 0.707, orthogonality completely lost. Modified Gram–Schmidt subtracts q₁ first, then measures q₂ᵀ(0, −ε, 0) = ε/√2, so v = (0, −ε/2, −ε/2) and q₃ = (0, −1, −1)/√2, with q₂ᵀq₃ = 0. Running both in double precision gives ‖I − QᵀQ‖ = 1.0 for the classical version and 1.4 × 10⁻⁸ for the modified one; κ(A) = 3.0 × 10⁸, so the modified version loses about κu ≈ 3.3 × 10⁻⁸, as Björck's bound says, while Householder QR would lose nothing beyond u.
-
CG's rate. Derive CG's bound 2((√κ − 1)/(√κ + 1))ᵏ from Chebyshev polynomials.
Solution
With x₀ = 0, CG's iterate xₖ minimizes ‖x − x*‖_A over the Krylov space 𝒦ₖ = span{b, Ab, …, Aᵏ⁻¹b}. Every x in it has error x − x* = p(A)(x₀ − x*) for a polynomial p of degree at most k with p(0) = 1, so ‖eₖ‖_A = min over such p of ‖p(A)e₀‖_A. Expand e₀ = Σ cᵢvᵢ in the orthonormal eigenvectors of A: ‖p(A)e₀‖²_A = Σ λᵢp(λᵢ)²cᵢ² ≤ maxᵢ p(λᵢ)² ‖e₀‖²_A, hence ‖eₖ‖_A ≤ min_p max over λ ∈ [λ_min, λ_max] of |p(λ)| times ‖e₀‖_A. Choose p(λ) = Tₖ((λ_max + λ_min − 2λ)/(λ_max − λ_min)) / Tₖ((λ_max + λ_min)/(λ_max − λ_min)), where Tₖ is the Chebyshev polynomial; it has p(0) = 1, and the numerator is at most 1 on the interval because |Tₖ| ≤ 1 on [−1, 1]. So ‖eₖ‖_A/‖e₀‖_A ≤ 1/Tₖ(z) with z = (κ + 1)/(κ − 1), κ = λ_max/λ_min. For z > 1, Tₖ(z) = ½[(z + √(z² − 1))ᵏ + (z − √(z² − 1))ᵏ] ≥ ½(z + √(z² − 1))ᵏ, and z + √(z² − 1) = (κ + 1 + 2√κ)/(κ − 1) = (√κ + 1)²/((√κ − 1)(√κ + 1)) = (√κ + 1)/(√κ − 1). Therefore ‖eₖ‖_A ≤ 2((√κ − 1)/(√κ + 1))ᵏ ‖e₀‖_A. For the 1,024-unknown Poisson grid, κ = 440.7, the ratio is 0.909, and reaching 10⁻⁸ needs k = ⌈ln(0.5 × 10⁻⁸)/ln 0.909⌉ = 201, the table's bound; CG took 101, since the bound ignores how the eigenvalues are spread inside the interval (and the instrument stops on the residual rather than the A-norm of the error).
-
Build. Write a two-grid solver for the 1D Poisson problem, and measure its convergence factor against n.
Solution
Solution notes. Take A = tridiag(−1, 2, −1) of size n = 2n_c + 1 (
scipy.sparse.diags, as initerative.smoothing_spectrum), so the coarse grid has n_c points at the odd fine points. One cycle: ν sweeps of weighted Jacobi with ω = ⅔ (iterative._jacobi); the residual r = b − Ax; full-weighting restriction r_c[i] = (r[2i] + 2r[2i + 1] + r[2i + 2])/4 (0-based); an exact coarse solve of tridiag(−1, 2, −1) e_c = 4r_c withscipy.sparse.linalg.spsolve(the factor 4 is (2h)²/h², because our matrices are h² times the operator, the same scalingiterative.vcycleapplies); linear interpolation back (coarse values at the odd points, averages of neighbours at the even ones, zero beyond the ends); x ← x + Pe_c; ν more sweeps. Measure the factor as the median ratio of successive residual norms, asiterative.multigrid_experimentdoes, for n = 15, 31, 63, …, 511 with a random b. Our check of this design gives exactly 1/9 ≈ 0.111 per cycle with ν = 1 at n = 31 and 127, and with ν = 2 a spectral radius of the cycle's error operator of 5/81 ≈ 0.062 at every n from 15 to 511 (measured residual ratios 0.05–0.06), against 0.987 at n = 15 and 0.99995 at n = 255 for one Jacobi sweep alone. The factor is independent of n because the smoother removes the upper half of the modes at a rate of at least ⅓ per sweep, and the coarse correction removes the smooth half almost exactly. A complete answer adds a test that the factor stays below, say, 0.2 for every n, then replaces the exact coarse solve by a recursive call to get a V-cycle. -
★ Research. Polynomial smoothed growth for elimination with partial pivoting.
Discussion. Open. The question is whether, for every n × n matrix A with ‖A‖ ≤ 1 and G Gaussian, Gaussian elimination with partial pivoting on A + σG has growth factor bounded by a polynomial in n and 1/σ with high probability. Our instrument shows the phenomenon: Wilkinson's 32 × 32 matrix grows by 2³¹, but with σ = 10⁻⁸ the median growth over 20 trials is 2.00, because the exponential case needs exact ties in every pivot column. Sankar, Spielman and Teng (2006) proved smoothed bounds for elimination without pivoting, where each Schur complement of a perturbed matrix can be analysed directly. With partial pivoting the row chosen at each step depends on the perturbation, so the later Schur complements are conditioned on the outcomes of earlier comparisons, and the independence those arguments use is lost; and the bound must hold for every A, including adversarial ones built to steer the pivot sequence. A good partial answer would be a quasi-polynomial bound, a polynomial bound for a natural restricted class (for example perturbations of Wilkinson-like matrices, or growth measured in the first few steps), or a bound on the expected logarithm of the growth; results for the purely Gaussian case, with no fixed matrix underneath, have recently been announced (H. Huang and K. Tikhomirov), and extending them to an arbitrary centre is the heart of the problem.
Notes and sources
Glossary
- condition number (relative), well and ill conditioned — how much a problem's answer moves, relatively, when its data moves; κ(A) = ‖A‖‖A⁻¹‖ = σ_max/σ_min for a matrix.
- forward error, backward error, backward stable, residual — how wrong the answer is; how far the data must move to make it exact; an algorithm whose backward error is a small multiple of u; b − Ax̂.
- unit roundoff u, Wilkinson's model — 2⁻⁵³ in double precision; fl(a ∘ b) = (a ∘ b)(1 + δ), |δ| ≤ u.
- LU factorization, partial pivoting, growth factor, Cholesky — elimination as A = LU; swapping up the largest entry of each column; the largest entry produced over the largest in A; A = LLᵀ for symmetric positive definite A.
- least squares, normal equations, QR, Householder mirror, Givens rotation, Gram–Schmidt (classical, modified) — the closest fit; AᵀAx = Aᵀb; orthogonal times triangular; a reflection I − 2vvᵀ; a plane rotation; orthogonalizing against the original or the updated column.
- singular value decomposition, numerical rank, truncated SVD, Tikhonov regularization, pseudo-inverse — A = UΣVᵀ; the number of singular values above a tolerance; dropping or damping the small ones; the shortest least-squares solution.
- power and inverse iteration, the QR algorithm, Hessenberg form, Wilkinson's shift, deflation — finding eigenvalues by iteration; zeros below the first subdiagonal; a shift from the trailing 2 × 2 block; splitting off a converged eigenvalue.
- Krylov space, conjugate gradients, A-norm, preconditioner (Jacobi, SSOR), Arnoldi, GMRES — span{b, Ab, …}; the optimal method for symmetric positive definite systems; √(eᵀAe); M ≈ A cheap to solve with; an orthonormal Krylov basis; minimal residuals without symmetry.
- sparse matrix, CSR, fill-in, minimum degree, nested dissection, reverse Cuthill–McKee — storing only nonzeros; values, column numbers, row pointers; new nonzeros created by elimination; orderings that limit it.
- weighted Jacobi, smoothing, restriction, interpolation (prolongation), V-cycle, algebraic multigrid — relaxation that damps rough error; moving residuals to a coarser grid and corrections back; the recursive cycle; coarse levels built from the matrix alone.
- bisection, secant method, Newton's method, order of convergence, basin of attraction, safeguarded root finder — bracketing; slopes through two points or from f′; digits multiplied per step; the starts that reach one root; Brent's combination of bisection and fast steps.
- interpolation, Runge's phenomenon, Chebyshev points, node polynomial, barycentric formula — a polynomial through samples; divergence at equispaced points; cos(jπ/n); ∏(x − xⱼ); evaluation in O(n) per point.
- quadrature: trapezoid, Simpson, Gauss–Legendre, adaptive, Monte Carlo — rules of order h², h⁴, degree 2n − 1; refining where the error estimate is large; random samples, σ/√N in any dimension.
- Runge–Kutta, embedded pair, step control, stiffness, stability region, A-stable, backward Euler — multi-stage steps; two orders from one set of slopes; |R(z)| ≤ 1; stable on the whole left half-plane.
- symplectic integrator, leapfrog (velocity Verlet), modified Hamiltonian — a step that keeps phase-space area; kick–drift–kick; the nearby energy it conserves almost exactly.
- BLAS (levels 1, 2, 3), arithmetic intensity, LAPACK, blocked factorization, mixed-precision iterative refinement, HPL, Top500 — vector, matrix–vector and matrix–matrix kernels; flops per byte; panels at level 2 and trailing updates at level 3; low-precision factors with high-precision residuals; the ranking benchmark.
- randomized SVD, oversampling, power iteration; smoothed analysis — a random sketch of the range; extra columns and multiplications by AAᵀ; worst cases surrounded by easy ones.
Sources
- L. N. Trefethen and D. Bau, Numerical Linear Algebra (1997); G. H. Golub and C. F. Van Loan, Matrix Computations (4th ed., 2013); N. J. Higham, Accuracy and Stability of Numerical Algorithms (2nd ed., 2002); J. W. Demmel, Applied Numerical Linear Algebra (1997).
- J. H. Wilkinson, Rounding Errors in Algebraic Processes (1963) and The Algebraic Eigenvalue Problem (1965).
- Y. Saad, Iterative Methods for Sparse Linear Systems (2nd ed., 2003); W. L. Briggs, V. E. Henson and S. F. McCormick, A Multigrid Tutorial (2nd ed., 2000).
- L. N. Trefethen, Approximation Theory and Approximation Practice (2013); E. Hairer, C. Lubich and G. Wanner, Geometric Numerical Integration (2nd ed., 2006).
- J. Dongarra and F. Sullivan, "Guest editors' introduction: the top 10 algorithms", Computing in Science and Engineering, January 2000.
- J. G. F. Francis, "The QR transformation", The Computer Journal 1961; M. R. Hestenes and E. Stiefel, "Methods of conjugate gradients for solving linear systems", J. Res. Nat. Bur. Standards 1952; Y. Saad and M. H. Schultz, "GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems", SIAM J. Sci. Stat. Comput. 1986.
- L. N. Trefethen and R. S. Schreiber, "Average-case stability of Gaussian elimination", SIAM J. Matrix Anal. Appl. 1990; A. Sankar, D. A. Spielman and S.-H. Teng, "Smoothed analysis of the condition numbers and growth factors of matrices", SIAM J. Matrix Anal. Appl. 2006.
- N. Halko, P.-G. Martinsson and J. A. Tropp, "Finding structure with randomness: probabilistic algorithms for constructing approximate matrix decompositions", SIAM Review 2011; E. Carson and N. J. Higham, "Accelerating the solution of linear systems by iterative refinement in three precisions", SIAM J. Sci. Comput. 2018.
About this partfrom its README
Part 52 of a sixty-one-part course in computer science (see the series plan and the syllabus), the second part of Act X, Horizons and Trust. In 2000 a journal named the ten algorithms that most shaped twentieth-century science and engineering, and eight of them compute with real numbers. With rounding in every operation, the question Part 4 left open is which answers we can trust; the answer separates a problem's conditioning from an algorithm's backward stability. We build the classic algorithms small enough to read, from pivoted elimination and Householder's mirrors to the shifted QR algorithm, conjugate gradients, multigrid, Newton's fractal, Chebyshev interpolation, stiff and symplectic integrators, and mixed-precision refinement, and run each one.
The instruments are in explainer/cs/numeric/ (tested in tests/test_cs52_numeric.py):
linalg.py: relative condition numbers of functions and of Hilbert matrices; forward against backward error on Hilbert systems; LU with and without partial pivoting, returning the growth factor; Wilkinson's matrix and growth on random matrices, and on Wilkinson's matrix perturbed by Gaussian noise; Cholesky; Householder QR (each mirror kept for drawing) and Givens rotations; classical and modified Gram–Schmidt; least squares by the normal equations against QR; the SVD of a blur matrix, with truncated-SVD regularization; and the randomized SVD of Halko, Martinsson and Tropp, timed against a full SVD.eigen.py: power and inverse iteration; Householder reduction to Hessenberg form; the QR algorithm, unshifted and with Wilkinson's shift, with deflation, recording the last subdiagonal entry at every step and the measured order of convergence.iterative.py: the 2D Poisson matrix; steepest descent and conjugate gradients, with Jacobi and SSOR preconditioners and CG's bound; GMRES on a nonsymmetric convection–diffusion problem; CSR storage; Cholesky fill-in under row-by-row, reverse Cuthill–McKee, minimum-degree and nested-dissection orderings (factored by SciPy's SuperLU); the weighted-Jacobi error spectrum in 1D; and a geometric multigrid V-cycle in 2D (full-weighting restriction, bilinear interpolation, two sweeps before and after).analysis.py: bisection, secant and Newton raced on √2; Newton's basins for z³ − 1; Runge's function interpolated at equispaced and Chebyshev points, evaluated by the barycentric formula; trapezoid, Simpson, Gauss–Legendre and Monte Carlo quadrature, and adaptive Simpson; Dormand–Prince RK45 with step control; stiffness against backward Euler; the stability regions of Euler, RK4 and backward Euler; and a thousand Kepler orbits by RK4 and by leapfrog.speed.py: BLAS levels 1, 2 and 3 timed through NumPy, with their arithmetic intensity; and iterative refinement with an LU factorization in single precision and residuals in double.
Chapter notes
- Hook. Dongarra and Sullivan's ten algorithms of the twentieth century (2000), eight of them numerical. Two equations, 10⁻²⁰x₁ + x₂ = 1 and x₁ + x₂ = 2, whose answer is almost exactly (1, 1): elimination as taught gives x₁ = 0, x₂ = 1; swapping the rows first gives 1 and 1. The problem is well conditioned; the algorithm was unstable. The part's six objectives.
- 1. Conditioning and stability. The relative condition number derived as κ = |x f′(x)/f(x)|, belonging to the problem alone. Four problems, computed: x − 1 at x = 1.000001 (κ = 1,000,001, Part 4's cancellation), √x (0.5), eˣ at x = 100 (100), tan x at x = 1.5707 (16,306); about log₁₀ κ of sixteen digits are lost. The matrix condition number ‖A‖‖A⁻¹‖ = σ_max/σ_min derived (Turing, 1948), and the unit circle turned into an ellipse. Hilbert's matrix: κ = 1.6 × 10⁴, 1.5 × 10¹⁰ and 1.6 × 10¹⁶ at sizes 4, 8 and 12, so about 12, 6 and 0 digits survive. Backward stability: the computed answer is the exact answer for nearby data.
- 2. Backward error analysis. Wilkinson's model fl(a ∘ b) = (a ∘ b)(1 + δ), |δ| ≤ u = 2⁻⁵³; a sum of three numbers is the exact sum of data changed by about two roundings. Forward error ≲ κ × backward error derived; for Ax = b the residual gives the backward error η = ‖r‖/(‖A‖‖x̂‖) exactly, and the forward error is at most κη. On Hilbert systems solved by LAPACK's pivoted elimination, η stays between 2.4 × 10⁻¹⁷ and 6.1 × 10⁻¹⁷, the forward error climbs from 2.0 × 10⁻¹³ at n = 4 to 0.055 at n = 12, always below κη; 12, 7 and 1 correct digits at sizes 4, 8 and 12.
- 3. Gaussian elimination. Elimination on a 3 × 3 example is A = LU with the multipliers 2, 4 and 3 in L; the cost Σ 2(n − k)² ≈ ⅔n³, triangular solves about n² each, and the inverse three times dearer ("to solve, never invert"). The tiny pivot [[ε, 1], [1, 1]]: at ε = 10⁻²⁰ the computed factors are the exact factors of a matrix with a 0 where the 1 was; the largest error without pivoting grows from 2.8 × 10⁻¹³ at ε = 10⁻⁴ to 1.0 at ε = 10⁻²⁰, with partial pivoting it stays at most 2.2 × 10⁻¹⁶. The growth factor ρ ≤ 2ⁿ⁻¹ derived and attained by Wilkinson's matrix (9.2 × 10¹⁸ at n = 64), against a mean of 4.2 and a largest of 6.4 over 50 random 64 × 64 matrices (Trefethen and Schreiber, 1990; why growth is small in practice is unproved). Cholesky derived on a 2 × 2 matrix; n³/3 flops against LU's 2n³/3 and Householder QR's 4n³/3.
- 4. Least squares and QR. The normal equations Aᵀ(b − Ax̂) = 0 from the perpendicular, and κ(AᵀA) = κ(A)². QR (Golub, 1965) solves Rx̂ = (Qᵀb)₁:ₙ with κ(R) = κ(A): on a tall fit at κ = 10², 10⁴, 10⁶ and 10⁸ the normal equations' error reaches 0.37 against QR's 3.5 × 10⁻¹⁰. Householder's mirror carries (3, 4) to (−5, 0) and the second column (1, 3) to (−3, 1); one mirror per column. Givens rotations, one zero at a time: our 3 × 3 example needs 2, not 3. Classical against modified Gram–Schmidt on Hilbert matrices: ‖I − QᵀQ‖ is 1.4 for the classical version at n = 8, 0.16 for the modified one at n = 12 (proportional to κ, Björck 1967), and at worst 2.0 × 10⁻¹⁵ for Householder.
- 5. The SVD. Rotate, stretch, rotate: A = UΣVᵀ and κ = σ₁/σₙ. The truncated sum is the best rank-k approximation (Eckart and Young, 1936). The eighty singular values of a blur matrix: 56 above the rounding level 80σ₁ε, 25 above the data's noise of 10⁻³. Undoing the blur of a two-box signal: κ(K) = 1.4 × 10¹⁶ and the naive solve's error is 1.1 × 10¹³ times the signal; truncation brings the error from 77 percent with one term to 19 percent at k = 23, then back up to 10¹³ with all eighty; Tikhonov's damping (1963). Golub–Kahan bidiagonalization (1965), the pseudo-inverse, and the SVD as the tool of last resort.
- 6. Eigenvalues: the QR algorithm. Eigenvalues are roots of det(A − λI); Abel (1824) and the companion matrix mean every eigenvalue algorithm must iterate. On a random symmetric 8 × 8 matrix, the power method with |λ₂/λ₁| = 0.66 needs 36 steps to reach 10⁻¹³; inverse iteration with a shift 0.3 away needs 8. The QR algorithm (Francis; Kublanovskaya, 1961) as a similarity, with the off-diagonal entries fading on a log scale: 623 iterations for all eight eigenvalues unshifted. Hessenberg (here tridiagonal) form, Wilkinson's shift and deflation: 16 iterations, not 623. The last subdiagonal entry goes 7.9 × 10⁻⁴ → 4.4 × 10⁻¹² → 2.8 × 10⁻³⁵ (about 3, 11 and 34 digits; measured orders 3.66 and 3.04), cubic convergence; the largest error against LAPACK's eigenvalues is 8.0 × 10⁻¹⁵ with shifts, 1.3 × 10⁻¹⁴ without.
- 7. Conjugate gradients. Solving as going downhill on φ(x) = ½xᵀAx − bᵀx; steepest descent zigzags in a narrow bowl, CG arrives in two steps. CG as the best point of the Krylov space in the A-norm, with conjugate directions (Hestenes and Stiefel, 1952), and our instrument's ten-line loop. The bound 2((√κ − 1)/(√κ + 1))ᵏ, so steps grow like √κ. On the Poisson problem with 256, 1,024 and 4,096 unknowns (κ = 116, 441, 1,712; residual to 10⁻⁸): steepest descent 897, 3,297 and over 8,000 steps; CG 52, 101 and 198, against bounds of 103, 201 and 396. Preconditioning: Jacobi changes nothing (the diagonal is all fours); SSOR with ω = 1.5 cuts CG to 16, 26 and 47. GMRES (Saad and Schultz, 1986) through Arnoldi on a nonsymmetric convection–diffusion problem with 1,024 unknowns: 10⁻⁸ in 82 steps.
- 8. Sparse matrices. Poisson's equation and the five-point stencil derived from Taylor series. CSR storage and its matrix–vector loop, limited by memory bandwidth: the 64 × 64 grid's 4,096 unknowns have 20,224 nonzeros, 259.1 kB in CSR against 134 MB dense. Fill-in by Parter's graph view (1961): an arrow matrix fills completely with the hub first and not at all with it last; row by row, the grid's Cholesky factor has 262,207 nonzeros, 13 times the matrix. Minimum degree (after Markowitz, 1957) and nested dissection (George, 1973). Measured with SciPy's SuperLU: 262,207 row by row, 180,832 for reverse Cuthill–McKee, 63,266 for minimum degree, 89,164 for our nested dissection; when the grid side doubles from 32, fill grows ×8.0, ×7.7, ×5.5 and ×5.5.
- 9. Multigrid. Weighted Jacobi on the 1D Poisson matrix with 63 unknowns multiplies sine mode k by 1 − (4/3)sin²(kπ/2(n + 1)): at most ⅓ on the upper half of the modes, 0.999 on mode 1. The error spectrum after 0, 1, 3 and 10 sweeps: mode 1 goes from 0.126 to 0.125, the upper half's largest from 1.96 to 2.9 × 10⁻⁵; relaxation smooths. A smooth mode on the fine grid is rough on the coarse one (Fedorenko, 1964; Brandt in the 1970s); the two-grid scheme, then recursion. The V-cycle on 2D Poisson with 225, 961, 3,969 and 16,129 unknowns: 0.20, 0.20, 0.21 and 0.21 per cycle, ten cycles to a few parts in 10⁸ on every grid. Work W(n) = cn + W(n/4) = (4/3)cn, against n³, n² and n^(3/2) for dense, banded and nested-dissection or CG solvers; algebraic multigrid.
- 10. Roots and Newton's fractal. Bisection gains one bit a step: 12.2 digits after 40 steps. Newton's step from the tangent and its quadratic error, from x₀ = 2 to 1.5 and 1.4167; the secant method's order 1.618. The race, computed: the secant method's digits 1.1, 1.8, 3.4, 5.7, 9.5, 15.7; Newton's 1.1, 2.6, 5.7, 11.8, 16.0; bisection 7.0 after 20 steps; per evaluation Newton's order is √2 and the secant method is faster. Newton's basins for z³ − 1 (Cayley, 1879) on 360 × 360 starts, 0.003 percent never settling in 40 steps; a window 15 times smaller on the boundary shows the same structure, one 300 times smaller inside a basin is flat, every start reaching the same root in 6 steps; hence safeguarded root finders such as Brent's (1973).
- 11. Approximation. Runge's phenomenon (1901) for 1/(1 + 25x²): the error at 11 equally spaced points is 1.92, at 21 points 59.8, at 81 points 6.3 × 10¹⁴. Chebyshev points from a semicircle; the error formula's node polynomial is 8.5 × 10⁻³ near the ends and 9.8 × 10⁻⁵ in the middle for 11 equispaced points, at most 1.9 × 10⁻³ ≈ 2¹⁻ⁿ for Chebyshev points. Geometric convergence: 0.018 with 21 Chebyshev points, 1.2 × 10⁻⁷ at degree 80 against 6.3 × 10¹⁴ equispaced, at the rate ρ = (1 + √26)/5 ≈ 1.220 set by the poles at ±i/5. The barycentric formula derived, O(n) per point and stable (Higham, 2004). Chebfun (Battles and Trefethen, 2004): sample on 17, 33, 65, … points until the coefficients reach rounding level; for Runge's function the rate predicts about 185.
- 12. Quadrature. The test integral ∫₀² eˣ cos 3x dx = −0.0099098. Trapezoids (error 0.274 with four) and Simpson's rule by cancelling the h² terms. Gauss's two-point rule derived (weights 1 at ±1/√3); n points exact to degree 2n − 1; Golub and Welsch (1969). Four rules computed: trapezoid 1.0 × 10⁻³ and Simpson 1.0 × 10⁻⁶ at 64 intervals, Gauss 4.1 × 10⁻¹⁵ with 16 points, Monte Carlo 0.64 with 65 samples (root mean square over 200 runs). Adaptive Simpson's error estimate (S₂ − S₁)/15: on √|x − 0.7| the accepted intervals crowd at the cusp (9 for a tolerance of 10⁻³, illustrative); on the smooth test integral at 10⁻¹⁰, 985 evaluations and an error of 2.3 × 10⁻¹⁴, where Gauss needed 16. Monte Carlo's σ/√N in any dimension against a grid's N^(−2/d): above d = 4 Monte Carlo wins.
- 13. Differential equations. Euler and RK4 on y′ = y, four steps of ½: 5.06 and 7.384 against e² = 7.389. Step control by Dormand and Prince's 5(4) pair (1980), SciPy's RK45. Stiffness on y′ = λ(y − cos t) − sin t over [0, 2]: adaptive RK45 at tolerance 10⁻⁶ takes 11, 132 (3 rejected) and 6,067 (214 rejected) steps for λ = −1, −100 and −10⁴; backward Euler takes 200 every time, with errors 2.2 × 10⁻³, 2.0 × 10⁻⁵ and 2.1 × 10⁻⁷. Stability regions computed: Euler reaches −2 on the real axis, RK4 about −2.8, backward Euler the whole left half-plane (A-stability, Dahlquist, 1963). Leapfrog as kick–drift–kick, a symplectic shear of phase space; a Kepler orbit of eccentricity 0.5 for 1,000 orbits at 100 steps each: RK4's orbit shrinks and its energy error reaches −2.99 percent and is still falling, leapfrog's turns but never exceeds 1.08 percent, and leapfrog is ahead from orbit 367. The modified Hamiltonian: backward error analysis again.
- 14. Speed: BLAS, LAPACK and mixed precision. Arithmetic intensity derived for the three BLAS levels: 1/12, ¼
and n/12 flops per byte (0.083, 0.25 and 21.3 at n = 256). Timed on this machine through NumPy (best of 3–5 runs,
on a shared machine): at n = 2,048,
axpy0.71,gemv26.69 andgemm289.3 GFLOP/s, sogemmruns 408 and 11 times faster than the other two. LAPACK's blocked LU: only the panels run at level 2, a fraction 3b/4n of the work (0.5 percent for n = 10,000 and b = 64). Mixed-precision refinement at κ = 10⁵, n = 400: correct digits 2.7 → 5.5 → 8.4 → 11.2 → 11.5, matching a full double-precision solve. HPL and the Top500 since 1993: Frontier's first exaflop (1.102 × 10¹⁸, June 2022) is 3.8 × 10⁶ times ourgemm; HPCG reaches a few percent of peak. - 15. Frontier: randomized and low-precision numerics. The randomized SVD (Halko, Martinsson and Tropp, 2011) on a 1,200 × 600 matrix at rank 20: with no extra columns the error is 2.77, 1.32 and 1.16 times the best possible after 0, 1 and 2 power steps (1.72, 2.02 and 1.98 s); with 10 extra columns 1.00 in each case (1.36, 3.55 and 2.50 s), against 69.1 s for a full SVD. Iterative refinement in low precision: at κ = 10² double-precision accuracy (5.4 × 10⁻¹⁵) in two steps, at κ = 10⁵ in three to four, at κ = 10⁸ the error grows from 1.06 to 357, since κ times single precision's epsilon exceeds one. Smoothed growth: Wilkinson's 32 × 32 matrix grows by 2,147,483,648, but plus 10⁻⁸ Gaussian noise by 2.00 (median and largest of 20); random 64 × 64 matrices grow by about 4; smoothed analysis (Spielman and Teng, 2001; Sankar, Spielman and Teng, 2006) and the missing theorem for partial pivoting. Four open problems (the exponent ω, stable fast solvers, low precision with guarantees, communication) and the ★ research problem.
- Outro. Recap, payoffs (Parts 51, 53, 54, 56 and 57), practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Conditioning: condition numbers for f(x) and for Ax = b (κ = ‖A‖‖A⁻¹‖), derived; stability.
- Backward error analysis (Wilkinson): forward error ≤ κ × backward error.
- Gaussian elimination as LU (2n³/3 flops); failure without pivoting on [[ε, 1], [1, 1]] (computed); partial pivoting, with a growth factor of 2ⁿ⁻¹ in the worst case and benign growth on average (Trefethen & Schreiber); Cholesky.
- Least squares: normal equations square κ; Householder QR (mirrors animated) and Givens rotations; classical against modified Gram–Schmidt (loss of orthogonality computed).
- The SVD as the tool of last resort (callback to AI, Built 3); rank and regularization.
- Eigenvalues: Abel–Ruffini, so iteration is the only way; inverse iteration; the QR algorithm (Francis 1961) with Hessenberg reduction, shifts, deflation and its final cubic convergence (computed).
- Krylov methods: conjugate gradient (Hestenes & Stiefel 1952) as optimization over Krylov spaces; the rate ((√κ − 1)/(√κ + 1))ᵏ; preconditioning; GMRES.
- Sparse matrices: CSR, fill-in, orderings (minimum degree, nested dissection); the Poisson problem.
- Multigrid: smoothing kills high frequencies and coarse grids handle the low ones, an O(n) solver (the error spectrum animated).
- Root finding: bisection, secant, Newton, and Newton's fractal for z³ − 1 (computed, zoomed).
- Approximation: Runge's phenomenon; Chebyshev points; barycentric interpolation; the Chebfun idea (Trefethen).
- Quadrature: Gauss, adaptive, Monte Carlo.
- ODEs: RK and step control; stiffness and A-stability; symplectic integrators conserve energy (leapfrog against RK4 over long orbits, computed).
- Speed: BLAS levels 1, 2 and 3 and arithmetic intensity (callbacks to Part 9 and AI, Built 17); LAPACK; mixed-precision iterative refinement; HPL and the Top500. Outro.
Computed: pivoting failures; growth factors; orthogonality loss; QR-algorithm convergence; CG against steepest descent; multigrid; the Newton fractal; Runge against Chebyshev; stiffness; orbit drift; BLAS timings on this machine. Visuals: Householder mirrors; subdiagonal entries fading under QR; the fractal zoom; the multigrid spectrum; drifting orbits. In practice: NumPy, SciPy and LAPACK; simulation and scientific computing; numerics in finance, engineering and ML training. Reading: Trefethen & Bau, Numerical Linear Algebra; Golub & Van Loan, Matrix Computations; Higham; Demmel, Applied Numerical Linear Algebra; Saad, Iterative Methods for Sparse Linear Systems; Briggs, Henson & McCormick, A Multigrid Tutorial; Trefethen, Approximation Theory and Approximation Practice; Hairer, Lubich & Wanner, Geometric Numerical Integration; Wilkinson, The Algebraic Eigenvalue Problem; Dongarra & Sullivan 2000.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
抵消。 证明 f(x) = x − 1 的相对条件数是 |x|/|x − 1|,并用它解释灾难性抵消。
解答
相对条件数是 κ(x) = |x f′(x)/f(x)|,而 f′(x) = 1,所以 κ = |x|/|x − 1|。远离 x = 1 时它接近 1,x → 1 时 无界:在 x = 1.000001 处为 1,000,001。仅仅对数据舍入一次,x ↦ fl(x),相对误差至多 u = 2⁻⁵³,就会使答案产生至多 κu ≈ 1.1 × 10⁻¹⁰ 的相对变化。在双精度下 fl(1.000001) − 1 = 9.999999999177334 × 10⁻⁷,相对误差 8.2 × 10⁻¹¹:十六位 中大约十位正确。减法本身是精确的(斯特本茨引理:若 y/2 ≤ x ≤ 2y,则 x − y 是一个浮点数),所以运算没有出错;x 与 1 的前几位相互抵消,剩下的正是早已被舍入破坏的那几位,被提升到了最前面。灾难性抵消是条件数大,而不是算法差:一般地, 相对于 x 和 y 的扰动,κ(x − y) = (|x| + |y|)/|x − y|,恰在 x ≈ y 时很大。补救办法是在相减之前改写公式(例如 √(x + 1) − √x = 1/(√(x + 1) + √x)),而不是更小心地相减。
-
增长。 证明部分主元(列主元)消去法的增长因子至多为 2ⁿ⁻¹,并证明威尔金森矩阵达到这个界。
解答
令 ρ 为所有阶段 k、所有 i、j 上 |a⁽ᵏ⁾ᵢⱼ| 的最大值除以 max |aᵢⱼ|。部分主元把第 k 列中绝对值最大的元素换到 主元位置,所以每个乘数都满足 |ℓᵢₖ| ≤ 1。第 k 步把 a⁽ᵏ⁾ᵢⱼ 换成 a⁽ᵏ⁺¹⁾ᵢⱼ = a⁽ᵏ⁾ᵢⱼ − ℓᵢₖa⁽ᵏ⁾ₖⱼ,因此 max |A⁽ᵏ⁺¹⁾| ≤ (1 + 1) max |A⁽ᵏ⁾|;n − 1 步之后,max |U| ≤ 2ⁿ⁻¹ max |A|。威尔金森矩阵 W 对角线上为 1,对角线以下 为 −1,最后一列为 1,其余为 0,所以 max |W| = 1。第 1 列的所有候选元素绝对值都是 1;若平局时保留已在原位的行(我们 的
lu中numpy.argmax正是如此),就不交换任何行,每个乘数都是 −1,于是下面每一行都加上第 1 行。这使第 1 列对角线 以下变为零,第 2 到 n − 1 列的 −1 保持不变(第 1 行在那里为零),并把第 1 行以下最后一列的元素从 1 加倍为 2。右下角 (n − 1) × (n − 1) 的块又是一个最后一列乘以 2 的威尔金森矩阵,所以归纳地,U 的最后一列是 1, 2, 4, …, 2ⁿ⁻¹, ρ = 2ⁿ⁻¹。我们的工具精确地证实了这一点:n = 4、8、16、32、64 时分别为 8、128、32,768、2,147,483,648 和 2⁶³ ≈ 9.2 × 10¹⁸。 -
格拉姆–施密特。 证明经典格拉姆–施密特与修正格拉姆–施密特在精确算术中相同,并给出一个在浮点运算中二者不同的 3 × 3 例子。
解答
经典格拉姆–施密特用 rᵢⱼ = qᵢᵀaⱼ;修正的版本用 rᵢⱼ = qᵢᵀv⁽ⁱ⁾,其中 v⁽ⁱ⁾ = aⱼ − Σₗ₍ₗ₌₁…ᵢ₋₁₎ rₗⱼqₗ 是 到目前为止更新过的列。对 i 归纳:若 q₁, …, qᵢ 标准正交,则 qᵢᵀv⁽ⁱ⁾ = qᵢᵀaⱼ − Σₗ rₗⱼ qᵢᵀqₗ = qᵢᵀaⱼ,因为 l < i 时 qᵢᵀqₗ = 0。所以系数、向量 v 以及归一化后的 qⱼ 都相同,标准正交性也传到下一列。在浮点运算中 qₗ 只是近似正交, qᵢᵀqₗ = 0 这一步不再成立。取 ε = 10⁻⁸,使 1 + ε² 舍入为 1,令 A = [[1, 1, 1], [ε, 0, 0], [0, ε, 0]](各列为 a₁ = (1, ε, 0),a₂ = (1, 0, ε),a₃ = (1, 0, 0))。两种版本都得到 q₁ = (1, ε, 0)(它的范数舍入为 1)和 q₂ = (0, −1, 1)/√2。对第三列,经典版本算出 q₁ᵀa₃ = 1、q₂ᵀa₃ = 0,于是 v = (0, −ε, 0),q₃ = (0, −1, 0): q₂ᵀq₃ = 1/√2 ≈ 0.707,正交性完全丧失。修正版本先减去 q₁,再计算 q₂ᵀ(0, −ε, 0) = ε/√2,于是 v = (0, −ε/2, −ε/2),q₃ = (0, −1, −1)/√2,q₂ᵀq₃ = 0。在双精度下运行两者,经典版本 ‖I − QᵀQ‖ = 1.0,修正版本为 1.4 × 10⁻⁸;κ(A) = 3.0 × 10⁸,所以修正版本损失约 κu ≈ 3.3 × 10⁻⁸,与 Björck 的界一致,而豪斯霍尔德 QR 的损失不会 超过 u 的量级。
-
共轭梯度法的收敛速度。 用切比雪夫多项式推导共轭梯度法的界 2((√κ − 1)/(√κ + 1))ᵏ。
解答
取 x₀ = 0,共轭梯度法的迭代 xₖ 在克雷洛夫子空间 𝒦ₖ = span{b, Ab, …, Aᵏ⁻¹b} 上最小化 ‖x − x*‖_A。其中每个 x 的误差都是 x − x* = p(A)(x₀ − x*),p 是次数至多为 k、满足 p(0) = 1 的多项式,所以 ‖eₖ‖_A 等于对所有这样的 p 取 ‖p(A)e₀‖_A 的最小值。把 e₀ = Σ cᵢvᵢ 按 A 的标准正交特征向量展开:‖p(A)e₀‖²_A = Σ λᵢp(λᵢ)²cᵢ² ≤ maxᵢ p(λᵢ)² ‖e₀‖²_A,因此 ‖eₖ‖_A ≤(对 p 取最小、对 λ ∈ [λ_min, λ_max] 取最大的 |p(λ)|)× ‖e₀‖_A。取 p(λ) = Tₖ((λ_max + λ_min − 2λ)/(λ_max − λ_min)) / Tₖ((λ_max + λ_min)/(λ_max − λ_min)),其中 Tₖ 是切比雪夫多项式; 它满足 p(0) = 1,并且因为在 [−1, 1] 上 |Tₖ| ≤ 1,分子在区间上至多为 1。所以 ‖eₖ‖_A/‖e₀‖_A ≤ 1/Tₖ(z),其中 z = (κ + 1)/(κ − 1),κ = λ_max/λ_min。当 z > 1 时,Tₖ(z) = ½[(z + √(z² − 1))ᵏ + (z − √(z² − 1))ᵏ] ≥ ½(z + √(z² − 1))ᵏ,而 z + √(z² − 1) = (κ + 1 + 2√κ)/(κ − 1) = (√κ + 1)²/((√κ − 1)(√κ + 1)) = (√κ + 1)/(√κ − 1)。 因此 ‖eₖ‖_A ≤ 2((√κ − 1)/(√κ + 1))ᵏ ‖e₀‖_A。对 1,024 个未知数的泊松网格,κ = 440.7,比值为 0.909,达到 10⁻⁸ 需要 k = ⌈ln(0.5 × 10⁻⁸)/ln 0.909⌉ = 201,正是表中的界;共轭梯度法用了 101 步,因为这个界不考虑特征值在区间内部如何分布 (而且工具以残差而不是误差的 A 范数作为停止标准)。
-
动手。 为一维泊松问题写一个两重网格求解器,并测量它的收敛因子随 n 的变化。
解答
解答要点。 取 n = 2n_c + 1 阶的 A = tridiag(−1, 2, −1)(用
scipy.sparse.diags,与iterative.smoothing_spectrum相同),粗网格的 n_c 个点位于细网格的奇数点上。一个循环:ν 次 ω = ⅔ 的加权雅可比迭代(iterative._jacobi);残差 r = b − Ax;全加权限制 r_c[i] = (r[2i] + 2r[2i + 1] + r[2i + 2])/4(下标从 0 开始);用scipy.sparse.linalg.spsolve精确求解粗网格方程 tridiag(−1, 2, −1) e_c = 4r_c(因子 4 是 (2h)²/h²,因为我们的矩阵是算子的 h² 倍,与iterative.vcycle的缩放相同);线性插值回细网格(奇数点取粗网格值,偶数点取相邻两值的平均,两端之外为零); x ← x + Pe_c;再做 ν 次迭代。像iterative.multigrid_experiment那样,把收敛因子取为相邻两次残差范数之比的中位数, 对 n = 15、31、63、…、511 和随机的 b 测量。我们按这个设计验证的结果:ν = 1 时在 n = 31 和 127 上每个循环恰为 1/9 ≈ 0.111;ν = 2 时,循环误差算子的谱半径在 n = 15 到 511 的每个 n 上都是 5/81 ≈ 0.062(实测残差比 0.05–0.06); 而单独一次雅可比迭代在 n = 15 时为 0.987,在 n = 255 时为 0.99995。收敛因子与 n 无关,因为光滑迭代以每次至少 ⅓ 的 速度消除上半部分的模态,而粗网格校正几乎精确地消除光滑的那一半。完整的答案应加一个测试,检查每个 n 上的因子都低于 (比如)0.2,然后把精确的粗网格求解换成递归调用,得到 V 循环。 -
★ 研究。 部分主元消去法的多项式光滑增长。
讨论。 尚未解决。问题是:对每个满足 ‖A‖ ≤ 1 的 n × n 矩阵 A 和高斯矩阵 G,对 A + σG 做部分主元高斯消元,其增长 因子是否以高概率受 n 和 1/σ 的一个多项式约束。我们的工具展示了这一现象:威尔金森的 32 × 32 矩阵增长 2³¹ 倍,但在 σ = 10⁻⁸ 时 20 次试验的增长中位数为 2.00,因为指数增长需要每个主元列中都恰好出现平局。Sankar、Spielman 和 Teng (2006)证明了不选主元消去法的光滑界,那里被扰动矩阵的每个舒尔补都可以直接分析。选部分主元时,每一步选中的行依赖于 扰动,于是后面的舒尔补是以前面各次比较的结果为条件的,那些论证所用的独立性就丧失了;而且这个界必须对每个 A 成立, 包括专门构造来操纵主元序列的对手矩阵。好的部分结果可以是一个拟多项式界、对某个自然的受限类(例如类威尔金森矩阵的 扰动,或只看前几步的增长)的多项式界,或对增长的对数的期望的界;对纯高斯情形(下面没有固定矩阵)的结果最近已有人 宣布(H. Huang 和 K. Tikhomirov),把它推广到任意的中心矩阵,正是问题的核心。
Build the film
python -m videos.cs.cs52.compute # the part's numbers, into .cache/cs52
python tools/build.py cs52 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs52 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs52. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs52.compute
python -m unittest tests.test_cs52_numeric
python tools/build.py cs52