Type at least 2 letters. Enter opens the first result, Esc closes.

    Linear Algebra · Lesson 14 · Numerical linear algebra

    Eigenvalue and SVD algorithms (QR algorithm, Golub–Kahan) and Krylov methods

    Advanced 90 min 6 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 05 (eigenvalues, power iteration), lesson 06 (spectral theorem, Rayleigh quotient), lesson 07 (positive definite matrices), lesson 12 (QR) and lesson 13 (floating point and conditioning). Time: about 90 minutes, plus the notebook.


    Why this matters #

    Nobody computes eigenvalues as the roots of det⁡(A−λI)\det(A - \lambda I). Polynomial roots are very sensitive to rounding in the coefficients, and for n≥5n \ge 5 there is no formula for them in radicals (Abel–Ruffini). So every eigenvalue algorithm iterates. Two families cover practice. Dense methods (the QR algorithm, Golub–Kahan for the SVD) find all eigenvalues of a matrix you can store, in O(n3)O(n^3) operations; they run inside np.linalg.eig, eigh and svd. Krylov methods only need the product v↦Avv \mapsto Av. They find a few eigenvalues or solve Ax=bAx = b for sparse or implicit matrices with millions of unknowns: the pressure-Poisson step of a fluid solver, the top eigenvalues of a network Hessian. CG also explains why the condition number decides how long such a solve takes.

    1. Predict first #

    2. The picture #

    Power iteration, two upgrades. Power iteration (lesson 05) repeats x←Ax/∥Ax∥x \leftarrow Ax/\|Ax\| and finds the dominant eigenvector at rate ∣λ2/λ1∣|\lambda_2/\lambda_1| per step. Two ideas improve it.

    • Change the matrix. (A−σI)−1(A - \sigma I)^{-1} has the same eigenvectors as AA and eigenvalues 1/(λi−σ)1/(\lambda_i - \sigma). The eigenvalue closest to the shift σ\sigma becomes the dominant one. This is inverse iteration. If you update σ\sigma at every step with the current estimate, you get Rayleigh quotient iteration.
    • Iterate many vectors at once. Multiply an orthonormal block of jj vectors by AA and re-orthonormalize it (QR). The block converges to the span of the top jj eigenvectors. With j=nj = n this is the QR algorithm.
    Interactive figure: loading…

    Move the shift σ\sigma. All three methods start from the same vector of a 5×55 \times 5 symmetric matrix. Power iteration falls at the slow rate ∣λ2/λ1∣=0.8|\lambda_2/\lambda_1| = 0.8 (0.96 for the second spectrum). Inverse iteration finds the eigenvalue closest to σ\sigma (the blue dot on the strip) at the rate ∣λJ−σ∣/∣λK−σ∣|\lambda_J - \sigma|/|\lambda_K - \sigma|: put σ\sigma near an eigenvalue and the line gets steep; put it halfway between two and it crawls. Rayleigh quotient iteration updates its shift every step and needs only a few.

    Quick check

    A symmetric matrix has eigenvalues 5,4,2,1,0.55, 4, 2, 1, 0.5. Inverse iteration uses the fixed shift σ=2.3\sigma = 2.3. Which eigenvalue does it find, and how fast?

    Keep every vector. Power iteration keeps only the last vector Ak−1bA^{k-1}b and throws away b,Ab,…,Ak−2bb, Ab, \dots, A^{k-2}b. A Krylov method keeps all of them and picks the best combination. Every vector in their span is p(A)bp(A)b for a polynomial pp of degree at most k−1k - 1. Power iteration always uses p(λ)=λk−1p(\lambda) = \lambda^{k-1}; a Krylov method chooses the best pp for the task. "Best" can be made precise, and that gives the convergence theory below.

    3. Definitions and main results #

    Inverse iteration and Rayleigh quotient iteration #

    Inverse iteration with shift σ\sigma: solve (A−σI)y=xk(A - \sigma I)y = x_k, set xk+1=y/∥y∥x_{k+1} = y/\|y\|. Factor A−σIA - \sigma I once (LU), then each step costs two triangular solves, O(n2)O(n^2); never form the inverse. Let λJ\lambda_J be the eigenvalue closest to σ\sigma and λK\lambda_K the next closest. The vector converges to ±vJ\pm v_J with error O(∣λJ−σ∣k/∣λK−σ∣k)O(|\lambda_J - \sigma|^k / |\lambda_K - \sigma|^k): a good shift gives a tiny ratio. The system is nearly singular when σ≈λJ\sigma \approx \lambda_J, but this is harmless: the large error in yy points along vJv_J, which is the direction we want.

    Rayleigh quotient iteration (RQI): use the shift σk=r(xk)=xk⊤Axk\sigma_k = r(x_k) = x_k^\top A x_k (with ∥xk∥=1\|x_k\| = 1), updated every step. For symmetric AA it converges cubically:

    1. If ∥xk−v∥=O(ϵ)\|x_k - v\| = O(\epsilon), the Rayleigh quotient is accurate to O(ϵ2)O(\epsilon^2) (lesson 06).
    2. One inverse-iteration step with a shift error O(ϵ2)O(\epsilon^2) multiplies the error by O(ϵ2)O(\epsilon^2).
    3. So ∥xk+1−v∥=O(ϵ3)\|x_{k+1} - v\| = O(\epsilon^3): the number of correct digits roughly triples per step.

    The price is a new factorization at every step. For non-symmetric AA the rate is quadratic.

    The QR algorithm #

    A0=A,Ak=QkRk (QR factorization),Ak+1=RkQk.A_0 = A, \qquad A_k = Q_kR_k \ \text{(QR factorization)}, \qquad A_{k+1} = R_kQ_k.

    Two vectors at a time, in words. Take A=(2112)A = \begin{pmatrix} 2 & 1 \\ 1 & 2\end{pmatrix}. Its eigenvectors are (1,1)/2(1, 1)/\sqrt2 (eigenvalue 3) and (−1,1)/2(-1, 1)/\sqrt2 (eigenvalue 1). Start with the two vectors e1,e2e_1, e_2.

    1. Power step. Multiply both by AA: Ae1=(2,1)Ae_1 = (2, 1) and Ae2=(1,2)Ae_2 = (1, 2).
    2. Re-orthonormalize with Gram–Schmidt: q1=(2,1)/5q_1 = (2, 1)/\sqrt5 and q2=(−1,2)/5q_2 = (-1, 2)/\sqrt5. Steps 1 and 2 together are one QR factorization of A[e1  e2]=AA[e_1\; e_2] = A.
    3. Repeat. The first vector does plain power iteration, so it turns toward the dominant eigenvector (1,1)/2(1, 1)/\sqrt2; the angle error shrinks by about 1/31/3 per step.
    4. The second vector must stay orthogonal to the first. In R2\mathbb{R}^2 it has only one place to go: the other eigenvector (−1,1)/2(-1, 1)/\sqrt2, up to sign.
    5. So Q‾=[q1  q2]\underline Q = [q_1\; q_2] tends to the eigenvector matrix, and Q‾⊤AQ‾\underline Q^\top A\underline Q tends to diag⁡(3,1)\operatorname{diag}(3, 1).

    In nn dimensions the first jj vectors do power iteration on a jj-dimensional subspace, so their span tends to the span of the top jj eigenvectors. The QR algorithm does not store these vectors. It updates the matrix Ak=Q‾k⊤A Q‾kA_k = \underline Q_k^\top A\,\underline Q_k directly, as the theorem shows.

    Theorem (the QR algorithm is simultaneous power iteration) #

    Let Q‾k=Q0Q1⋯Qk−1\underline{Q}_k = Q_0Q_1\cdots Q_{k-1} and R‾k=Rk−1⋯R1R0\underline{R}_k = R_{k-1}\cdots R_1R_0. Then (a) Ak=Q‾k⊤A Q‾kA_k = \underline{Q}_k^\top A\,\underline{Q}_k, and (b) Ak=Q‾kR‾kA^k = \underline{Q}_k\underline{R}_k.

    Proof.

    1. From Ak=QkRkA_k = Q_kR_k: Rk=Qk⊤AkR_k = Q_k^\top A_k, so Ak+1=RkQk=Qk⊤AkQkA_{k+1} = R_kQ_k = Q_k^\top A_kQ_k. Repeating this from A0=AA_0 = A gives (a). Each step is an orthogonal similarity: same eigenvalues, and a symmetric AA stays symmetric.
    2. For (b), use induction. k=1k = 1: A=Q0R0A = Q_0R_0. Assume Ak=Q‾kR‾kA^k = \underline{Q}_k\underline{R}_k. By (a), AQ‾k=Q‾kAkA\underline{Q}_k = \underline{Q}_kA_k. So Ak+1=AQ‾kR‾k=Q‾kAkR‾k=Q‾kQkRkR‾k=Q‾k+1R‾k+1A^{k+1} = A\underline{Q}_k\underline{R}_k = \underline{Q}_kA_k\underline{R}_k = \underline{Q}_kQ_kR_k\underline{R}_k = \underline{Q}_{k+1}\underline{R}_{k+1}.
    3. R‾k\underline{R}_k is upper triangular (with a nonzero diagonal if AA is nonsingular), so (b) is a QR factorization of AkA^k. The first jj columns of Q‾k\underline{Q}_k are an orthonormal basis of the span of the first jj columns of AkA^k, that is, of Akspan⁡(e1,…,ej)A^k\operatorname{span}(e_1, \dots, e_j): power iteration on a jj-dimensional subspace. ■\blacksquare

    Convergence. Let AA be symmetric with ∣λ1∣>∣λ2∣>⋯>∣λn∣|\lambda_1| > |\lambda_2| > \dots > |\lambda_n|, and let all leading principal submatrices of its eigenvector matrix be nonsingular (true for almost every AA). Then AkA_k tends to diag⁡(λ1,…,λn)\operatorname{diag}(\lambda_1, \dots, \lambda_n), ordered by decreasing ∣λ∣|\lambda|, and Q‾k\underline{Q}_k tends to the eigenvectors (up to signs). The entry (j+1,j)(j+1, j) decays like ∣λj+1/λj∣k|\lambda_{j+1}/\lambda_j|^k: linear convergence, slow when two eigenvalues are close in modulus. For a real non-symmetric AA the limit is the real Schur form: upper triangular, with 2×22\times2 blocks for complex-conjugate pairs.

    The hidden inverse iteration. For symmetric AA, invert (b): A−k=R‾k−1Q‾k⊤A^{-k} = \underline{R}_k^{-1}\underline{Q}_k^\top, and since A−kA^{-k} is symmetric, A−k=Q‾kR‾k−⊤A^{-k} = \underline{Q}_k\underline{R}_k^{-\top} with R‾k−⊤\underline{R}_k^{-\top} lower triangular. Its last column gives A−ken∝Q‾kenA^{-k}e_n \propto \underline{Q}_k e_n. So the last column of Q‾k\underline{Q}_k runs inverse iteration. This is why a shift taken from the bottom-right corner works so well.

    Answers to section 1, question 2. The off-diagonal entry shrinks by λ2/λ1=1/3\lambda_2/\lambda_1 = 1/3 per step, asymptotically (section 4 shows 1→0.6→0.22→0.0741 \to 0.6 \to 0.22 \to 0.074). For (0110)\begin{pmatrix} 0 & 1 \\ 1 & 0\end{pmatrix} nothing happens: Q0=AQ_0 = A, R0=IR_0 = I, so A1=AA_1 = A. The eigenvalues ±1\pm1 have equal modulus, and the ratio is 1.

    Quick check

    A symmetric 3×33 \times 3 matrix has eigenvalues 4,2,14, 2, 1. In the unshifted QR algorithm, by what factor does the entry (3,2)(3, 2) of AkA_k shrink per step (asymptotically)?

    The practical eigenvalue pipeline #

    1. Reduce once to Hessenberg form. Householder reflections give A=QHQ⊤A = QHQ^\top with HH zero below the first subdiagonal, in about 103n3\tfrac{10}{3}n^3 flops. A symmetric AA becomes tridiagonal (about 43n3\tfrac43 n^3 flops). Triangular form cannot be reached in a finite number of steps (for n≥5n \ge 5 it would give the eigenvalues in closed form, see Abel–Ruffini); Hessenberg is the closest form one can reach.
    2. QR steps keep the form and are cheap. If H=QRH = QR is Hessenberg, then Q=HR−1Q = HR^{-1} and RQRQ are Hessenberg too. One step costs O(n2)O(n^2) with n−1n - 1 Givens rotations instead of O(n3)O(n^3); on a tridiagonal matrix, O(n)O(n).
    3. Shifts. Ak−μkI=QkRkA_k - \mu_kI = Q_kR_k, Ak+1=RkQk+μkIA_{k+1} = R_kQ_k + \mu_kI. This is still a similarity: Ak+1=Qk⊤(Ak−μkI)Qk+μkI=Qk⊤AkQkA_{k+1} = Q_k^\top(A_k - \mu_kI)Q_k + \mu_kI = Q_k^\top A_kQ_k. The Rayleigh shift μk=(Ak)nn\mu_k = (A_k)_{nn} is, for symmetric AA, RQI on the last column (hidden inverse iteration). It fails on (0110)\begin{pmatrix} 0 & 1 \\ 1 & 0\end{pmatrix} (μ=0\mu = 0, no progress). The Wilkinson shift is the eigenvalue of the trailing 2×22\times2 block that is closer to (Ak)nn(A_k)_{nn}. For symmetric tridiagonal matrices it always converges (Wilkinson, 1968), at least quadratically and in practice cubically.
    4. Deflation. When ∣hn,n−1∣≤ε (∣hn−1,n−1∣+∣hnn∣)|h_{n,n-1}| \le \varepsilon\,(|h_{n-1,n-1}| + |h_{nn}|), set it to 0. Then hnnh_{nn} is an eigenvalue; continue on the leading (n−1)×(n−1)(n-1)\times(n-1) block.
    5. Real non-symmetric matrices have complex pairs. The Francis double-shift step uses the two eigenvalues of the trailing 2×22\times2 block as shifts in one real step, applied implicitly ("bulge chasing").
    Interactive figure: loading…

    Press Run, then change the shift. The chart follows the subdiagonal entries of AkA_k on a log scale, and the heat map shows AkA_k (stronger colour = larger ∣aij∣|a_{ij}|). Without a shift each entry decays at its own rate ∣λj+1/λj∣|\lambda_{j+1}/\lambda_j| (dashed) and the whole run takes about 100 steps. With the Rayleigh or Wilkinson shift the corner entry drops below 10−1410^{-14} in a few steps, the block deflates (dashed frame), and the next corner starts: all four eigenvalues take 13 steps with the Rayleigh shift and 7 with the Wilkinson shift. Try the zero-diagonal matrix: the Rayleigh shift is 0, so the corner does not move until rounding errors break the symmetry (the first eigenvalue deflates after about 37 steps); the Wilkinson shift finishes in 8.

    The SVD pipeline: Golub–Kahan #

    We want orthogonal U,VU, V with U⊤AVU^\top AV diagonal. The SVD is not a similarity (UU and VV can differ), so a finite procedure can reach more than Hessenberg form: a bidiagonal matrix BB, with nonzeros only on the diagonal and the first superdiagonal. Golub–Kahan bidiagonalization does this with Householder reflections from the left and from the right: A=UBV⊤A = UBV^\top.

    • Why this is the right form. B⊤B=V⊤A⊤AVB^\top B = V^\top A^\top AV is tridiagonal: Golub–Kahan tridiagonalizes A⊤AA^\top A without forming it.
    • Phase 2. The singular values of BB are computed by an implicitly shifted QR iteration on BB itself, or by divide and conquer.
    • Why not eig⁡(A⊤A)\operatorname{eig}(A^\top A). Forming A⊤AA^\top A squares the condition number (lesson 13). Its computed eigenvalues have absolute errors of about εσ12\varepsilon\sigma_1^2, so every singular value below about ε σ1≈1.5×10−8σ1\sqrt{\varepsilon}\,\sigma_1 \approx 1.5\times10^{-8}\sigma_1 is lost (section 5 shows 10−1010^{-10} coming out as 10−810^{-8}).
    Golub–Kahan step by step, and which LAPACK routine NumPy calls

    For m≥nm \ge n the reflections alternate: from the left, zero column jj below the diagonal; from the right, zero row jj to the right of the superdiagonal. For a 4×34 \times 3 matrix (×\times = nonzero):

    (××××××××××××)→U1⊤(×××0××0××0××)→V1(××00××0××0××)→U2⊤(××00××00×00×)→U3⊤(××00××00×000)\begin{pmatrix}\times&\times&\times\\\times&\times&\times\\\times&\times&\times\\\times&\times&\times\end{pmatrix} \xrightarrow{U_1^\top} \begin{pmatrix}\times&\times&\times\\0&\times&\times\\0&\times&\times\\0&\times&\times\end{pmatrix} \xrightarrow{V_1} \begin{pmatrix}\times&\times&0\\0&\times&\times\\0&\times&\times\\0&\times&\times\end{pmatrix} \xrightarrow{U_2^\top} \begin{pmatrix}\times&\times&0\\0&\times&\times\\0&0&\times\\0&0&\times\end{pmatrix} \xrightarrow{U_3^\top} \begin{pmatrix}\times&\times&0\\0&\times&\times\\0&0&\times\\0&0&0\end{pmatrix}

    The right reflection V1V_1 acts on columns 2–3 only, so it does not refill column 1. The cost is about 4mn2−43n34mn^2 - \tfrac43 n^3 flops. For m≫nm \gg n it is cheaper to compute A=QRA = QR first and bidiagonalize the n×nn \times n matrix RR (about 2mn2+2n32mn^2 + 2n^3 flops).

    Phase 2 is either the implicitly shifted QR iteration on BB (Golub–Kahan–Reinsch; LAPACK driver gesvd) or divide and conquer (gesdd, the NumPy and SciPy default). So NumPy's SVD is Golub–Kahan bidiagonalization followed by divide and conquer, not a QR iteration; the QR driver is available as scipy.linalg.svd(..., lapack_driver="gesvd").

    For eigenvalues: np.linalg.eig calls LAPACK geev (Hessenberg reduction, then Francis QR); np.linalg.eigh calls syevd (tridiagonal reduction, then divide and conquer); scipy.linalg.eigh uses syevr (tridiagonal reduction, then the MRRR method) by default. The QR algorithm is the core for non-symmetric matrices; for symmetric ones it is one of several choices after the reduction.

    Krylov subspaces and the Arnoldi relation #

    The Krylov subspace of A∈Rn×nA \in \mathbb{R}^{n\times n} and b∈Rnb \in \mathbb{R}^n is

    Kk(A,b)=span⁡{b,Ab,A2b,…,Ak−1b}={p(A)b:deg⁡p≤k−1}.\mathcal K_k(A, b) = \operatorname{span}\{b, Ab, A^2b, \dots, A^{k-1}b\} = \{p(A)b : \deg p \le k - 1\}.

    Building it needs only matrix-vector products.

    Why the plain basis is bad. The vectors b,Ab,A2b,…b, Ab, A^2b, \dots are the iterates of power iteration. So they all turn toward the dominant eigenvector, and after a few steps they are almost parallel. A basis of almost parallel vectors is extremely ill-conditioned: small rounding errors in the vectors change the coefficients completely.

    Interactive figure: loading…

    Move kk, then switch to the Hessenberg view. Top: the condition number of the plain basis [b,Ab,…,Ak−1b][b, Ab, \dots, A^{k-1}b] (each vector scaled to length 1) grows by about 6 times per step and comes close to 1/u1/u (numerically singular) by k=20k = 20; the Arnoldi basis QkQ_k spans the same space and keeps κ(Qk)=1\kappa(Q_k) = 1. Bottom: the angle between Ak−1bA^{k-1}b and the top eigenvector falls toward 0. In the Hessenberg view, press Next step: each Arnoldi step adds one column to H~k\tilde H_k. Switch to a symmetric matrix and the entries above the first superdiagonal become 0.

    Arnoldi builds an orthonormal basis of the same space, one vector at a time. It orthogonalizes each new vector AqjAq_j against the old ones (modified Gram–Schmidt, lesson 12):

    q1=b/∥b∥q_1 = b/\|b\|; for j=1,…,kj = 1, \dots, k: w=Aqjw = Aq_j; for i=1,…,ji = 1, \dots, j: hij=qi⊤wh_{ij} = q_i^\top w, w←w−hijqiw \leftarrow w - h_{ij}q_i; then hj+1,j=∥w∥h_{j+1,j} = \|w\|, qj+1=w/hj+1,jq_{j+1} = w/h_{j+1,j}.

    The loop as equations, for k=2k = 2. Rearrange each step: what was subtracted plus what is left gives back AqjAq_j.

    • Step j=1j = 1: Aq1=h11q1+h21q2Aq_1 = h_{11}q_1 + h_{21}q_2.
    • Step j=2j = 2: Aq2=h12q1+h22q2+h32q3Aq_2 = h_{12}q_1 + h_{22}q_2 + h_{32}q_3.

    Put the two equations side by side as columns:

    A(q1q2)=(q1q2q3)(h11h12h21h220h32),that is,AQ2=Q3H~2.A\begin{pmatrix} q_1 & q_2\end{pmatrix} = \begin{pmatrix} q_1 & q_2 & q_3\end{pmatrix} \begin{pmatrix} h_{11} & h_{12} \\ h_{21} & h_{22} \\ 0 & h_{32}\end{pmatrix}, \qquad\text{that is,}\qquad AQ_2 = Q_3\tilde H_2 .

    The 0 in the bottom-left corner is there because Aq1Aq_1 needs only q1q_1 and q2q_2. In general AqjAq_j needs only q1,…,qj+1q_1, \dots, q_{j+1}, so H~k\tilde H_k is zero below its first subdiagonal: it is upper Hessenberg.

    Theorem (Arnoldi relation) #

    If no hj+1,jh_{j+1,j} is zero, the columns of Qk=[q1⋯qk]Q_k = [q_1 \cdots q_k] (n×kn \times k) are an orthonormal basis of Kk(A,b)\mathcal K_k(A, b), and

    AQk=Qk+1H~kequivalentlyAQk=QkHk+hk+1,k qk+1ek⊤,AQ_k = Q_{k+1}\tilde H_k \quad\text{equivalently}\quad AQ_k = Q_kH_k + h_{k+1,k}\,q_{k+1}e_k^\top,

    with Qk+1Q_{k+1} of size n×(k+1)n\times(k+1), H~k\tilde H_k of size (k+1)×k(k+1)\times k upper Hessenberg, and Hk=Qk⊤AQkH_k = Q_k^\top AQ_k its top k×kk \times k block.

    Proof.

    1. Step jj of the loop, rearranged, reads Aqj=∑i=1j+1hijqiAq_j = \sum_{i=1}^{j+1} h_{ij}q_i. This is column jj of AQk=Qk+1H~kAQ_k = Q_{k+1}\tilde H_k, with hij=0h_{ij} = 0 for i>j+1i > j + 1: upper Hessenberg.
    2. By construction qj+1q_{j+1} is orthogonal to q1,…,qjq_1, \dots, q_j and has norm 1.
    3. By induction, qj+1∈span⁡(q1,…,qj,Aqj)⊆Kj+1q_{j+1} \in \operatorname{span}(q_1, \dots, q_j, Aq_j) \subseteq \mathcal K_{j+1}. The kk orthonormal vectors lie in Kk\mathcal K_k, whose dimension is at most kk, so they are a basis.
    4. Multiply AQk=QkHk+hk+1,kqk+1ek⊤AQ_k = Q_kH_k + h_{k+1,k}q_{k+1}e_k^\top by Qk⊤Q_k^\top. Since Qk⊤qk+1=0Q_k^\top q_{k+1} = 0: Qk⊤AQk=HkQ_k^\top AQ_k = H_k. ■\blacksquare
    • Ritz values. HkH_k is AA compressed onto Kk\mathcal K_k. Its eigenvalues θ\theta (Ritz values) approximate eigenvalues of AA, the extreme ones first. For an eigenpair Hky=θyH_ky = \theta y with ∥y∥=1\|y\| = 1, the residual is ∥AQky−θQky∥=hk+1,k∣ek⊤y∣\|AQ_ky - \theta Q_ky\| = h_{k+1,k}|e_k^\top y|: a free error estimate.
    • Breakdown hj+1,j=0h_{j+1,j} = 0 means Kj\mathcal K_j is invariant under AA: the Ritz values are exact eigenvalues ("lucky" breakdown).
    • Cost. kk products with AA, about 2nk22nk^2 flops of orthogonalization, nknk numbers of memory. ARPACK (eigs, eigsh) restarts to bound kk.
    • Lanczos. If AA is symmetric, Hk=Qk⊤AQkH_k = Q_k^\top AQ_k is symmetric and Hessenberg, so it is tridiagonal: TkT_k with diagonal αj\alpha_j and off-diagonal βj\beta_j. The loop collapses to the three-term recurrence βjqj+1=Aqj−αjqj−βj−1qj−1\beta_jq_{j+1} = Aq_j - \alpha_jq_j - \beta_{j-1}q_{j-1}, with O(n)O(n) work per step beyond the product. In floating point the qjq_j lose orthogonality as soon as a Ritz value converges (Paige), and copies ("ghosts") of converged eigenvalues appear. Full or selective reorthogonalization fixes this.
    Interactive figure: loading…

    Move kk or press Play. Each column holds the kk Ritz values of a 200×200200 \times 200 symmetric matrix after kk Lanczos steps; the ticks on the right are its eigenvalues. The isolated eigenvalues 2.0 and 1.5 are found first, then the edges of the dense block [0,1][0, 1]; the interior never converges in 60 steps. Switch off reorthogonalization and go past k≈30k \approx 30: a stray Ritz value climbs up and becomes a second copy of 2.0 (a ghost).

    Conjugate gradient #

    Let AA be SPD, x∗=A−1bx^* = A^{-1}b, error e=x−x∗e = x - x^*, residual r=b−Ax=−Aer = b - Ax = -Ae, and ∥e∥A=e⊤Ae\|e\|_A = \sqrt{e^\top Ae} (the AA-norm, or energy norm).

    • Energy. φ(x)=12x⊤Ax−b⊤x=12∥x−x∗∥A2−12x∗⊤Ax∗\varphi(x) = \tfrac12 x^\top Ax - b^\top x = \tfrac12\|x - x^*\|_A^2 - \tfrac12 x^{*\top}Ax^*. Minimizing φ\varphi is minimizing the AA-norm error, and −∇φ(x)=r-\nabla\varphi(x) = r.
    • Definition. The CG iterate is xk=argmin⁡{∥x−x∗∥A:x∈x0+Kk(A,r0)}x_k = \operatorname{argmin}\{\|x - x^*\|_A : x \in x_0 + \mathcal K_k(A, r_0)\}.
    • Optimality = orthogonal residual. xkx_k is this minimizer exactly when (xk−x∗)⊤Av=0(x_k - x^*)^\top Av = 0 for all v∈Kkv \in \mathcal K_k, that is, rk⊥Kkr_k \perp \mathcal K_k.
    • The algorithm finds xkx_k with short recurrences and one product ApAp per step:
    r0=p0=b−Ax0,αk=rk⊤rkpk⊤Apk,xk+1=xk+αkpk,rk+1=rk−αkApk,r_0 = p_0 = b - Ax_0,\quad \alpha_k = \frac{r_k^\top r_k}{p_k^\top Ap_k},\quad x_{k+1} = x_k + \alpha_kp_k,\quad r_{k+1} = r_k - \alpha_kAp_k,
    βk=rk+1⊤rk+1rk⊤rk,pk+1=rk+1+βkpk.\beta_k = \frac{r_{k+1}^\top r_{k+1}}{r_k^\top r_k},\quad p_{k+1} = r_{k+1} + \beta_kp_k.

    The residuals are mutually orthogonal and the directions are AA-conjugate (pi⊤Apj=0p_i^\top Ap_j = 0 for i≠ji \ne j). In an AA-orthogonal basis the minimization splits into one-dimensional problems, so adding a new direction never changes the old coefficients: progress is never undone. CG is Lanczos applied to Ax=bAx = b.

    • Why SPD. Positive definiteness makes ∥⋅∥A\|\cdot\|_A a norm and φ\varphi strictly convex; symmetry gives the short recurrence.

    CG as a polynomial problem. Every xkx_k in x0+Kkx_0 + \mathcal K_k has an error of the form ek=p(A)e0e_k = p(A)e_0, where pp has degree at most kk and p(0)=1p(0) = 1 (step 1 of the proof below). In the eigenvector basis, p(A)p(A) multiplies the component of e0e_0 along viv_i by p(λi)p(\lambda_i). So CG is fast when some polynomial with p(0)=1p(0) = 1 is small at every eigenvalue of AA:

    • eigenvalues spread over [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]: pp must be small on the whole interval, and the best one can do depends on κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} through κ\sqrt\kappa;
    • eigenvalues in a few clusters: put one root of pp in each cluster;
    • only dd distinct eigenvalues: put a root on each, and pp is exactly 0 on the spectrum.
    Interactive figure: loading…

    Change the spectrum and move kk. The blue curve is the CG polynomial pkp_k: it starts at pk(0)=1p_k(0) = 1 and its roots (blue dots) are the Ritz values. CG makes pkp_k small at the eigenvalues (the ticks). The orange scaled Chebyshev polynomial is the best one can do knowing only [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]; the dashed lines at ±1/Tk(⋅)\pm 1/T_k(\cdot) give the bound. With 3 distinct values CG is exact after 3 steps; with outliers three roots go to the outliers first, and then CG converges as if κ\kappa were 2.

    Theorem (CG convergence) #

    ∥ek∥A∥e0∥A=min⁡deg⁡p≤kp(0)=1∥p(A)e0∥A∥e0∥A≤min⁡deg⁡p≤kp(0)=1 max⁡λ∈σ(A)∣p(λ)∣≤2(κ−1κ+1)k,κ=λmax⁡λmin⁡.\frac{\|e_k\|_A}{\|e_0\|_A} = \min_{\substack{\deg p \le k\\ p(0) = 1}}\frac{\|p(A)e_0\|_A}{\|e_0\|_A} \le \min_{\substack{\deg p \le k\\ p(0) = 1}}\ \max_{\lambda \in \sigma(A)}|p(\lambda)| \le 2\Big(\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\Big)^k, \qquad \kappa = \frac{\lambda_{\max}}{\lambda_{\min}}.

    Proof.

    1. xk−x0∈Kk(A,r0)x_k - x_0 \in \mathcal K_k(A, r_0) and r0=−Ae0r_0 = -Ae_0, so xk−x0=−q(A)Ae0x_k - x_0 = -q(A)Ae_0 with deg⁡q≤k−1\deg q \le k - 1. Then ek=(I−Aq(A))e0=p(A)e0e_k = (I - Aq(A))e_0 = p(A)e_0 with p(λ)=1−λq(λ)p(\lambda) = 1 - \lambda q(\lambda): degree ≤k\le k, p(0)=1p(0) = 1. Every such pp arises from some qq.
    2. CG minimizes ∥ek∥A\|e_k\|_A over this set, which gives the equality.
    3. Write e0=∑icivie_0 = \sum_i c_iv_i in orthonormal eigenvectors of AA. Then ∥p(A)e0∥A2=∑ici2λip(λi)2≤max⁡ip(λi)2∑ici2λi=max⁡ip(λi)2 ∥e0∥A2\|p(A)e_0\|_A^2 = \sum_i c_i^2\lambda_ip(\lambda_i)^2 \le \max_i p(\lambda_i)^2\sum_i c_i^2\lambda_i = \max_i p(\lambda_i)^2\,\|e_0\|_A^2.
    4. The last inequality: choose one good polynomial (the scaled Chebyshev polynomial) and bound its maximum on [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]. Details in the folded proof. ■\blacksquare
    Step 4: the Chebyshev polynomial bound

    The Chebyshev polynomial TkT_k has degree kk, satisfies ∣Tk(z)∣≤1|T_k(z)| \le 1 on [−1,1][-1, 1], and grows fastest outside [−1,1][-1, 1] among such polynomials. Map [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}] onto [−1,1][-1, 1] and normalize so that p(0)=1p(0) = 1:

    p(λ)=Tk(λmax⁡+λmin⁡−2λλmax⁡−λmin⁡)/Tk(κ+1κ−1).p(\lambda) = T_k\Big(\tfrac{\lambda_{\max} + \lambda_{\min} - 2\lambda}{\lambda_{\max} - \lambda_{\min}}\Big)\Big/T_k\Big(\tfrac{\kappa + 1}{\kappa - 1}\Big).
    1. At λ=0\lambda = 0 the argument is λmax⁡+λmin⁡λmax⁡−λmin⁡=κ+1κ−1\tfrac{\lambda_{\max} + \lambda_{\min}}{\lambda_{\max} - \lambda_{\min}} = \tfrac{\kappa + 1}{\kappa - 1}, so p(0)=1p(0) = 1.
    2. For λ∈[λmin⁡,λmax⁡]\lambda \in [\lambda_{\min}, \lambda_{\max}] the argument lies in [−1,1][-1, 1], so the numerator is at most 1 in absolute value, and max⁡λ∈σ(A)∣p(λ)∣≤1/Tk(κ+1κ−1)\max_{\lambda \in \sigma(A)} |p(\lambda)| \le 1/T_k\big(\tfrac{\kappa + 1}{\kappa - 1}\big).
    3. For z≥1z \ge 1, Tk(z)=12[(z+z2−1)k+(z−z2−1)k]≥12(z+z2−1)kT_k(z) = \tfrac12\big[(z + \sqrt{z^2 - 1})^k + (z - \sqrt{z^2 - 1})^k\big] \ge \tfrac12(z + \sqrt{z^2 - 1})^k.
    4. For z=κ+1κ−1z = \tfrac{\kappa + 1}{\kappa - 1}: z2−1=4κ(κ−1)2z^2 - 1 = \tfrac{4\kappa}{(\kappa - 1)^2}, so z+z2−1=κ+1+2κκ−1=(κ+1)2(κ+1)(κ−1)=κ+1κ−1z + \sqrt{z^2 - 1} = \tfrac{\kappa + 1 + 2\sqrt\kappa}{\kappa - 1} = \tfrac{(\sqrt\kappa + 1)^2}{(\sqrt\kappa + 1)(\sqrt\kappa - 1)} = \tfrac{\sqrt\kappa + 1}{\sqrt\kappa - 1}.
    5. Steps 2–4 give max⁡∣p∣≤2(κ−1κ+1)k\max|p| \le 2\big(\tfrac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\big)^k. ■\blacksquare

    Consequences:

    • Iterations. About 12κ ln⁡(2/tol)\tfrac12\sqrt\kappa\,\ln(2/\text{tol}), so O(κ)O(\sqrt\kappa).
    • Steepest descent (exact line search) only reaches ∥ek∥A≤(κ−1κ+1)k∥e0∥A\|e_k\|_A \le \big(\tfrac{\kappa - 1}{\kappa + 1}\big)^k\|e_0\|_A: about 12κln⁡(1/tol)\tfrac12\kappa\ln(1/\text{tol}) iterations, O(κ)O(\kappa). CG replaces κ\kappa by κ\sqrt\kappa.
    • Few distinct eigenvalues. If AA has dd distinct eigenvalues, p(λ)=∏i(1−λ/λi)p(\lambda) = \prod_i(1 - \lambda/\lambda_i) vanishes on the spectrum, so CG is exact after at most dd steps (exact arithmetic). Clustered eigenvalues give fast convergence; I+(rank 5)I + (\text{rank } 5) needs about 6 steps.
    • Preconditioning. With an SPD M≈AM \approx A that is cheap to invert (Jacobi, incomplete Cholesky, multigrid), CG on the preconditioned system converges with κ(M−1A)\kappa(M^{-1}A) instead.
    Quick check

    A=I+UU⊤A = I + UU^\top is 1000×10001000 \times 1000, with UU of size 1000×51000 \times 5 and full column rank. In exact arithmetic, at most how many CG steps solve Ax=bAx = b?

    Interactive figure: loading…

    Drag x0x_0 and raise κ\kappa. On the contours of φ(x)=12x⊤Ax−b⊤x\varphi(x) = \tfrac12 x^\top Ax - b^\top x, steepest descent zigzags: each step stops where its line touches a contour, so the next gradient is perpendicular to it. CG takes the same first step, then a direction that is AA-conjugate to it, and reaches x∗x^* after 2 steps (n=2n = 2). The default start is the worst case for κ=10\kappa = 10: steepest descent meets its bound ((κ−1)/(κ+1))k((\kappa - 1)/(\kappa + 1))^k.

    Answers to section 1, question 1. CG: 12104ln⁡(2×106)≈725\tfrac12\sqrt{10^4}\ln(2\times10^6) \approx 725 iterations (the bound; in practice often fewer). Steepest descent: 12⋅104ln⁡(106)≈69,000\tfrac12 \cdot 10^4\ln(10^6) \approx 69{,}000.

    Quick check

    An SPD system has κ=100\kappa = 100. Using the standard bounds, about how many iterations do CG and steepest descent need to reduce the AA-norm error by 10−610^{-6}?

    GMRES #

    For any nonsingular AA, GMRES chooses xk∈x0+Kk(A,r0)x_k \in x_0 + \mathcal K_k(A, r_0) with the smallest residual ∥b−Axk∥2\|b - Ax_k\|_2. Write xk=x0+Qkyx_k = x_0 + Q_ky with the Arnoldi basis (q1=r0/βq_1 = r_0/\beta, β=∥r0∥\beta = \|r_0\|). Then b−Axk=r0−AQky=Qk+1(βe1−H~ky)b - Ax_k = r_0 - AQ_ky = Q_{k+1}(\beta e_1 - \tilde H_ky), and since Qk+1Q_{k+1} has orthonormal columns, ∥b−Axk∥=∥βe1−H~ky∥\|b - Ax_k\| = \|\beta e_1 - \tilde H_ky\|: a small (k+1)×k(k+1)\times k least-squares problem, updated by one Givens rotation per step.

    • The residual norms never increase (the spaces are nested).
    • No short recurrence: step kk costs O(nk)O(nk) and all kk vectors are stored. In practice one restarts every mm steps (GMRES(mm)), which can stagnate.
    • Symmetric indefinite systems use MINRES (the same minimization with a Lanczos short recurrence).
    method matrix minimizes over x0+Kkx_0 + \mathcal K_k recurrence work per step
    CG SPD ∥x−x∗∥A\lVert x - x^*\rVert_A short (Lanczos) 1 product + O(n)O(n)
    MINRES symmetric ∥b−Ax∥2\lVert b - Ax\rVert_2 short (Lanczos) 1 product + O(n)O(n)
    GMRES any nonsingular ∥b−Ax∥2\lVert b - Ax\rVert_2 full (Arnoldi) 1 product + O(nk)O(nk)
    The GMRES bound and non-normal matrices

    For diagonalizable A=XΛX−1A = X\Lambda X^{-1}, the same polynomial argument as for CG gives

    ∥rk∥∥r0∥≤κ(X)min⁡deg⁡p≤kp(0)=1 max⁡λ∈σ(A)∣p(λ)∣.\frac{\|r_k\|}{\|r_0\|} \le \kappa(X)\min_{\substack{\deg p \le k\\ p(0) = 1}}\ \max_{\lambda\in\sigma(A)}|p(\lambda)|.

    The rate depends on where the eigenvalues lie in the complex plane and on the non-normality κ(X)\kappa(X), not on κ(A)\kappa(A) alone. Eigenvalues in a disk that does not contain 0 give linear convergence (section 5 shows a disk of radius 0.5 around 1: the residual halves each step). For strongly non-normal matrices (κ(X)\kappa(X) huge) the eigenvalues can be misleading, and GMRES can stagnate for many steps before it converges.

    4. Worked example #

    A. QR steps by hand. A=(2112)A = \begin{pmatrix} 2 & 1 \\ 1 & 2\end{pmatrix}, eigenvalues 3 and 1.

    Gram–Schmidt on the columns: q1=(2,1)/5q_1 = (2, 1)/\sqrt5, r11=5r_{11} = \sqrt5, r12=q1⊤(1,2)=4/5r_{12} = q_1^\top(1, 2) = 4/\sqrt5. The remainder (1,2)−45(2,1)=(−35,65)(1, 2) - \tfrac45(2, 1) = (-\tfrac35, \tfrac65) has norm 3/53/\sqrt5, so q2=(−1,2)/5q_2 = (-1, 2)/\sqrt5:

    Q0=15(2−112),R0=15(5403),A1=R0Q0=(2.80.60.61.2).Q_0 = \tfrac{1}{\sqrt5}\begin{pmatrix} 2 & -1 \\ 1 & 2\end{pmatrix},\quad R_0 = \tfrac{1}{\sqrt5}\begin{pmatrix} 5 & 4 \\ 0 & 3\end{pmatrix},\quad A_1 = R_0Q_0 = \begin{pmatrix} 2.8 & 0.6 \\ 0.6 & 1.2\end{pmatrix}.

    Check: trace 44 and determinant 3.36−0.36=33.36 - 0.36 = 3 are unchanged. The diagonal moves toward (3,1)(3, 1). Further unshifted steps give off-diagonal magnitudes 0.6→0.220→0.0740→0.02470.6 \to 0.220 \to 0.0740 \to 0.0247: the ratio approaches 1/31/3.

    Shifted steps. For (abbc)\begin{pmatrix} a & b \\ b & c\end{pmatrix} with the Rayleigh shift μ=c\mu = c: with d=a−cd = a - c and ρ=d2+b2\rho = \sqrt{d^2 + b^2}, the QR factors of (dbb0)\begin{pmatrix} d & b \\ b & 0\end{pmatrix} are Q=1ρ(d−bbd)Q = \tfrac1\rho\begin{pmatrix} d & -b \\ b & d\end{pmatrix} and R=(ρdb/ρ0−b2/ρ)R = \begin{pmatrix}\rho & db/\rho \\ 0 & -b^2/\rho\end{pmatrix}. The (2,1)(2,1) entry of RQRQ is −b3/(d2+b2)-b^3/(d^2 + b^2). When bb is small, the new ∣b∣|b| is about ∣b∣3/d2|b|^3/d^2: cubic. From A1A_1 (d=1.6d = 1.6, b=0.6b = 0.6): ∣b∣=0.6→0.216/2.92=0.0740→1.0×10−4→2.6×10−13|b| = 0.6 \to 0.216/2.92 = 0.0740 \to 1.0\times10^{-4} \to 2.6\times10^{-13}. Three shifted steps reach this level; unshifted steps from A1A_1 would need 26. The exact second iterate is A2=1365(10942727366)A_2 = \tfrac{1}{365}\begin{pmatrix}1094 & 27\\27 & 366\end{pmatrix}. (The Wilkinson shift of a 2×22\times2 matrix is an exact eigenvalue, so it deflates in one step.)

    Quick check

    With the Rayleigh shift, the off-diagonal entry of this 2×22\times2 example goes 0.6→0.074→1.0×10−40.6 \to 0.074 \to 1.0\times10^{-4}, and the diagonal gap is now d≈2d \approx 2. What is the next value, roughly?

    B. CG by hand. A=(4113)A = \begin{pmatrix} 4 & 1 \\ 1 & 3\end{pmatrix} (SPD, κ≈1.94\kappa \approx 1.94), b=(1,2)b = (1, 2), x0=0x_0 = 0. The solution is x∗=(1/11,7/11)x^* = (1/11, 7/11), and ∥e0∥A=165/11≈1.168\|e_0\|_A = \sqrt{165}/11 \approx 1.168.

    Step 0.

    1. r0=b−Ax0=(1,2)r_0 = b - Ax_0 = (1, 2) and p0=r0=(1,2)p_0 = r_0 = (1, 2).
    2. Ap0=(4+2,  1+6)=(6,7)Ap_0 = (4 + 2,\; 1 + 6) = (6, 7).
    3. α0=r0⊤r0/p0⊤Ap0=(1+4)/(6+14)=5/20=1/4\alpha_0 = r_0^\top r_0 / p_0^\top Ap_0 = (1 + 4)/(6 + 14) = 5/20 = 1/4.
    4. x1=x0+α0p0=(1/4,1/2)x_1 = x_0 + \alpha_0p_0 = (1/4, 1/2).
    5. r1=r0−α0Ap0=(1−6/4,  2−7/4)=(−1/2,1/4)r_1 = r_0 - \alpha_0Ap_0 = (1 - 6/4,\; 2 - 7/4) = (-1/2, 1/4). Check: r0⊤r1=−1/2+1/2=0r_0^\top r_1 = -1/2 + 1/2 = 0.
    6. β0=r1⊤r1/r0⊤r0=(1/4+1/16)/5=(5/16)/5=1/16\beta_0 = r_1^\top r_1 / r_0^\top r_0 = (1/4 + 1/16)/5 = (5/16)/5 = 1/16.
    7. p1=r1+β0p0=(−1/2+1/16,  1/4+2/16)=(−7/16,3/8)p_1 = r_1 + \beta_0p_0 = (-1/2 + 1/16,\; 1/4 + 2/16) = (-7/16, 3/8).

    Step 1.

    1. Ap1=(−28/16+6/16,  −7/16+18/16)=(−11/8,11/16)Ap_1 = (-28/16 + 6/16,\; -7/16 + 18/16) = (-11/8, 11/16).
    2. Conjugacy check: p0⊤Ap1=1⋅(−11/8)+2⋅(11/16)=0p_0^\top Ap_1 = 1\cdot(-11/8) + 2\cdot(11/16) = 0.
    3. p1⊤Ap1=(−7/16)(−11/8)+(3/8)(11/16)=77/128+33/128=110/128p_1^\top Ap_1 = (-7/16)(-11/8) + (3/8)(11/16) = 77/128 + 33/128 = 110/128.
    4. α1=r1⊤r1/p1⊤Ap1=(5/16)/(110/128)=4/11\alpha_1 = r_1^\top r_1 / p_1^\top Ap_1 = (5/16)/(110/128) = 4/11.
    5. x2=x1+α1p1=(1/4−7/44,  1/2+3/22)=(1/11,7/11)=x∗x_2 = x_1 + \alpha_1p_1 = (1/4 - 7/44,\; 1/2 + 3/22) = (1/11, 7/11) = x^*.
    6. r2=r1−α1Ap1=(−1/2+1/2,  1/4−1/4)=(0,0)r_2 = r_1 - \alpha_1Ap_1 = (-1/2 + 1/2,\; 1/4 - 1/4) = (0, 0).

    What to notice:

    • Step 0 is the best point on the line span⁡{b}=K1\operatorname{span}\{b\} = \mathcal K_1: α0=b⊤b/b⊤Ab\alpha_0 = b^\top b/b^\top Ab. Its error is ∥e1∥A≈0.337\|e_1\|_A \approx 0.337.
    • After n=2n = 2 steps CG is exact, because K2=R2\mathcal K_2 = \mathbb{R}^2.
    • Steepest descent from the same start also has x1=(0.25,0.5)x_1 = (0.25, 0.5), but then x2=(1/12,7/12)x_2 = (1/12, 7/12) with ∥e2∥A≈0.097\|e_2\|_A \approx 0.097, and x3=(5/48,5/8)x_3 = (5/48, 5/8) with ∥e3∥A≈0.028\|e_3\|_A \approx 0.028: it zigzags and is never exact.

    5. In code #

    SciPy checks the worked example and shows the facts of this lesson:

    import numpy as np
    from scipy.linalg import hessenberg, schur, svd
    
    # The worked example: one QR step is an orthogonal similarity
    A = np.array([[2., 1.], [1., 2.]])
    Q0 = np.array([[2., -1.], [1., 2.]]) / np.sqrt(5)       # Gram-Schmidt Q of A
    R0 = np.array([[5., 4.], [0., 3.]]) / np.sqrt(5)
    A1 = R0 @ Q0
    print(np.allclose(Q0 @ R0, A), A1.round(12).tolist())    # True [[2.8, 0.6], [0.6, 1.2]]
    print(np.allclose(A1, Q0.T @ A @ Q0), np.linalg.eigvalsh(A1))  # True [1. 3.]
    
    # Phase 1 of eig: Hessenberg form (symmetric input: tridiagonal form)
    rng = np.random.default_rng(0)
    M = rng.standard_normal((6, 6))
    H, Qh = hessenberg(M, calc_q=True)
    print(np.abs(np.tril(H, -2)).max(), np.allclose(Qh @ H @ Qh.T, M))   # 0.0 True
    T = hessenberg(M + M.T)
    print(np.abs(np.triu(T, 2)).max() < 1e-12)                          # True: tridiagonal
    
    # The end point: real Schur form M = Z T Zᵀ, quasi-triangular (2x2 blocks = complex pairs)
    Tm, Z = schur(M)
    print(np.allclose(Z @ Tm @ Z.T, M), np.round(np.diag(Tm, -1), 3))   # True, nonzeros only in 2x2 blocks
    
    # SVD: two LAPACK drivers agree; eig(BᵀB) loses the small singular value
    Qa, _ = np.linalg.qr(rng.standard_normal((50, 4)))
    Qb, _ = np.linalg.qr(rng.standard_normal((4, 4)))
    B = Qa @ np.diag([1, 1e-3, 1e-6, 1e-10]) @ Qb.T
    s_dd = svd(B, compute_uv=False, lapack_driver="gesdd")   # bidiagonalize + divide and conquer
    s_qr = svd(B, compute_uv=False, lapack_driver="gesvd")   # bidiagonalize + implicit QR iteration
    s_eig = np.sqrt(np.abs(np.linalg.eigvalsh(B.T @ B)))[::-1]
    print(s_dd)          # [1.e+00 1.e-03 1.e-06 1.e-10] (the last one to about 7 digits)
    print(s_qr)          # the same
    print(s_eig)         # last entry 1.0e-08: rounding noise, not 1e-10
    

    Krylov methods, with only products v↦Avv \mapsto Av:

    import numpy as np
    import scipy.sparse as sp
    from scipy.sparse.linalg import cg, gmres, eigsh, LinearOperator
    
    def poisson_2d(n):                       # 5-point Laplacian on an n x n grid, size n² x n²
        T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(n, n))
        I = sp.identity(n)
        return (sp.kron(I, T) + sp.kron(T, I)).tocsr()
    
    rng = np.random.default_rng(0)
    
    # 1) CG iterations grow like sqrt(kappa): kappa = cot²(pi h / 2) with h = 1/(n+1)
    for n in (16, 32, 64, 128):
        A, b, it = poisson_2d(n), rng.standard_normal(n * n), [0]
        x, info = cg(A, b, rtol=1e-8, callback=lambda xk: it.__setitem__(0, it[0] + 1))
        kappa = 1 / np.tan(np.pi / (2 * (n + 1))) ** 2
        print(f"size {n*n:6d}  sqrt(kappa) {np.sqrt(kappa):5.1f}  CG iterations {it[0]:4d}")
    # size 256: 10.8, 52 · 1024: 21.0, 101 · 4096: 41.4, 198 · 16384: 82.1, 385  (about 4.8 sqrt(kappa))
    
    # 2) Few distinct eigenvalues: I + (rank 5) has at most 6, so CG needs about 6 steps
    N = 2000
    U = rng.standard_normal((N, 5))
    b, it = rng.standard_normal(N), [0]
    x, info = cg(np.eye(N) + U @ U.T, b, rtol=1e-10, callback=lambda xk: it.__setitem__(0, it[0] + 1))
    print("I + rank 5:", it[0], "iterations")                     # 6
    
    # 3) Lanczos (ARPACK eigsh) with only products v -> Xᵀ(Xv): PCA without forming XᵀX
    m, n = 20000, 1000
    X = rng.standard_normal((m, n))
    X += rng.standard_normal((m, 3)) @ np.diag([6.0, 4.0, 3.0]) @ np.linalg.qr(rng.standard_normal((n, 3)))[0].T
    calls = [0]
    def gram(v):
        calls[0] += 1
        return X.T @ (X @ v)
    top = eigsh(LinearOperator((n, n), matvec=gram, dtype=float), k=3, which="LA", return_eigenvectors=False)
    print(np.allclose(np.sort(top), np.linalg.eigvalsh(X.T @ X)[-3:]), calls[0], "products")   # True 21 products
    
    # 4) GMRES: residuals never increase; rate set by the eigenvalues (here a disk of radius 0.5 around 1)
    n = 1000
    A = np.eye(n) + 0.5 * rng.standard_normal((n, n)) / np.sqrt(n)
    res = []
    x, info = gmres(A, rng.standard_normal(n), rtol=1e-10, restart=200, maxiter=1,
                    callback=lambda r: res.append(r), callback_type="pr_norm")
    print(len(res), "iterations", np.round(res[:4], 3), bool(np.all(np.diff(res) <= 0)))
    # 33 iterations [0.447 0.226 0.109 0.055] True: each step about halves the residual
    

    For the 2-D Poisson matrix κ≈4/(πh)2\kappa \approx 4/(\pi h)^2 grows like h−2h^{-2}, so κ\sqrt\kappa and the CG iteration count double when the grid spacing halves. This is why fluid and climate solvers precondition with multigrid, which makes the count almost independent of the grid.

    6. Where it shows up #

    • Hessian spectra in deep learning. Lanczos with Hessian-vector products (lesson 15) gives the top eigenvalues of a network Hessian without forming it. The largest one bounds stable learning rates (η<2/λmax⁡\eta < 2/\lambda_{\max} for gradient descent on a quadratic).
    • Gaussian processes. GPyTorch solves K−1yK^{-1}y with preconditioned CG and estimates log⁡det⁡K\log\det K with Lanczos, using only kernel matrix-vector products.
    • ML for science. Pressure-Poisson solves in incompressible flow (CG with multigrid); implicit time steps of climate and ocean models (Jacobian-free Newton–Krylov: GMRES with Jacobian-vector products only); inverse problems (LSQR, which is Golub–Kahan bidiagonalization built from Krylov vectors); spectral clustering of a sensor graph and the leading EOFs of a huge ensemble (eigsh, svds).

    7. Common mistakes #

    • Mixing up the QR factorization and the QR algorithm. The algorithm repeats factorizations; one factorization gives no eigenvalues.
    • Unshifted QR on a dense matrix. O(n3)O(n^3) per step and linear convergence. Reduce to Hessenberg/tridiagonal form first, shift, and deflate.
    • CG on a matrix that is not SPD. It can stall or diverge. Use GMRES (any matrix), MINRES (symmetric indefinite), or CG on the normal equations only if squaring κ\kappa is acceptable.
    • The plain Krylov basis b,Ab,A2b,…b, Ab, A^2b, \dots It is numerically rank deficient after a few steps; always orthonormalize (Arnoldi, Lanczos).
    • Expecting exact arithmetic. CG does not stop exactly after nn steps, and plain Lanczos shows ghost eigenvalues. Stop on the residual (a small residual can hide a large error when κ\kappa is large, lesson 13).

    8. Check yourself #

    1. Show that one shifted QR step Ak−μI=QkRkA_k - \mu I = Q_kR_k, Ak+1=RkQk+μIA_{k+1} = R_kQ_k + \mu I keeps the eigenvalues.
      AnswerRk=Qk⊤(Ak−μI)R_k = Q_k^\top(A_k - \mu I), so Ak+1=Qk⊤(Ak−μI)Qk+μI=Qk⊤AkQkA_{k+1} = Q_k^\top(A_k - \mu I)Q_k + \mu I = Q_k^\top A_kQ_k: an orthogonal similarity.
    2. A symmetric matrix has eigenvalues 10, 9 and 1. In the unshifted QR algorithm, which subdiagonal entry converges slowly, and about how many steps does it need to shrink by 10−810^{-8}?
      AnswerEntry (2,1)(2,1) decays like (9/10)k(9/10)^k: ln⁡10−8/ln⁡0.9≈175\ln 10^{-8}/\ln 0.9 \approx 175 steps. Entry (3,2)(3,2) decays like (1/9)k(1/9)^k: about 9 steps. A shift near 9 or 10 removes the problem.
    3. Why is AA reduced to Hessenberg form before the QR iteration, and not to triangular form?
      AnswerThe one-time reduction costs O(n3)O(n^3), after which each QR step costs O(n2)O(n^2) (O(n)O(n) if tridiagonal) and keeps the form. Triangular form would reveal the eigenvalues, which no finite sequence of operations can do for n≥5n \ge 5.
    4. Write the Arnoldi relation with the shapes of all matrices. What changes when AA is symmetric?
      AnswerAQk=Qk+1H~kAQ_k = Q_{k+1}\tilde H_k: AA is n×nn\times n, QkQ_k is n×kn\times k, Qk+1Q_{k+1} is n×(k+1)n\times(k+1) with orthonormal columns, H~k\tilde H_k is (k+1)×k(k+1)\times k upper Hessenberg, and Hk=Qk⊤AQkH_k = Q_k^\top AQ_k. For symmetric AA, HkH_k is tridiagonal (Lanczos, three-term recurrence).
    5. κ(A)=106\kappa(A) = 10^6. Use the bounds to compare CG with steepest descent for a 10−810^{-8} reduction of the AA-norm error.
      AnswerCG: 12κln⁡(2×108)≈9,600\tfrac12\sqrt\kappa\ln(2\times10^8) \approx 9{,}600 iterations. Steepest descent: 12κln⁡108≈9.2×106\tfrac12\kappa\ln 10^8 \approx 9.2\times10^6. A preconditioner that lowers κ\kappa helps both, CG through κ\sqrt\kappa.
    6. An SPD matrix of size 3000 has only the eigenvalues 1, 2 and 3. How many CG steps are needed in exact arithmetic?
      AnswerAt most 3: p(λ)=(1−λ)(1−λ/2)(1−λ/3)p(\lambda) = (1 - \lambda)(1 - \lambda/2)(1 - \lambda/3) has degree 3, p(0)=1p(0) = 1, and is zero on the spectrum.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Inverse iteration with shift σ\sigma: which eigenvector does it find, and at what rate?

    2. How fast does Rayleigh quotient iteration converge for a symmetric matrix, and why?

    3. Why does one QR step Ak+1=RkQkA_{k+1} = R_kQ_k keep the eigenvalues?

    4. Why is AA reduced to Hessenberg form before the QR iteration?

    5. What is the Wilkinson shift?

    6. Define the Krylov subspace Kk(A,b)\mathcal K_k(A, b).

    7. State the Arnoldi relation.

    8. What does the Arnoldi matrix HkH_k become when AA is symmetric, and what is the method called?

    9. What does CG minimize, and what does GMRES minimize, over x0+Kkx_0 + \mathcal K_k?

    10. Give the CG convergence bound with κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}.

    Open the review →

    9. Interview angle #

    • "How does np.linalg.eig work?" — Householder reduction to Hessenberg form, then the shifted (Francis) QR algorithm with deflation; eigh reduces to tridiagonal form and uses divide and conquer; svd bidiagonalizes (Golub–Kahan) and uses divide and conquer (gesdd).
    • "Solve a sparse SPD system with 10610^6 unknowns." — CG with a preconditioner (multigrid, incomplete Cholesky): O(κ)O(\sqrt{\kappa}) iterations of one sparse product each, O(n)O(n) memory. For a 2-D problem, a sparse Cholesky with a fill-reducing ordering is also good.
    • "Top eigenvector of a huge matrix or of a Hessian?" — Lanczos (or power iteration) with matrix-vector (Hessian-vector) products only.
    • "CG versus gradient descent?" — on a quadratic, CG picks the optimal polynomial: κ\sqrt\kappa instead of κ\kappa. Momentum methods (heavy ball, Nesterov) also reach a κ\sqrt\kappa rate.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write inverse iteration with one LU factorization, and check its rate ∣λJ−σ∣/∣λK−σ∣|\lambda_J - \sigma|/|\lambda_K - \sigma|.
    2. Write Rayleigh quotient iteration and watch the number of correct digits triple.
    3. Write the unshifted QR algorithm, record the subdiagonal entries, and compare their decay with ∣λj+1/λj∣k|\lambda_{j+1}/\lambda_j|^k.
    4. Write Lanczos with full reorthogonalization, check AQk=QkTk+βkqk+1ek⊤AQ_k = Q_kT_k + \beta_kq_{k+1}e_k^\top, and compare the Ritz values with the extreme eigenvalues of a 1-D Laplacian.
    5. Write conjugate gradients, solve a 1-D Poisson problem, and compare its iteration count with steepest descent.

    11. Watch and read #

    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play