Module contents
Lesson 6 of 26Advanced 110 min

Computing eigenvalues and the SVD

Compute eigenvalues iteratively, from power iteration to the shifted QR algorithm used by LAPACK. Study SVD computation without forming AᵀA, eigenvalue sensitivity and the pseudospectra of nonnormal matrices.

After this lesson you can

  • Implement power, inverse and Rayleigh quotient iteration and measure their convergence orders.
  • Implement QR iteration with Hessenberg reduction, Wilkinson shifts and deflation.
  • Explain how LAPACK computes an SVD and why eigenvalues of AᵀA are avoided.
  • Use Bauer–Fike to predict eigenvalue sensitivity and recognize nonnormal matrices.
  • Compute PageRank on a real graph by sparse power iteration.

Before you start

Motivation: four eigenvalue problems

Run np.linalg.eigh(C) on a covariance matrix and its principal components appear in milliseconds. Behind that are sixty years of numerical analysis, and almost nothing from eigenvalue theory survives as an algorithm: neither the characteristic polynomial nor solving (A−λI)v=0(\mat{A} - \lambda\mat{I})\vb{v} = \vb{0} by elimination. Before seeing what replaces them, here are four problems these tools will solve:

  • PageRank. A page’s importance is a component of an eigenvector of a transition matrix with billions of rows. It does not fit in memory as a dense matrix, but can be multiplied by a vector: power iteration from the first section solves it (you will study PageRank on graphs).
  • Vibration modes. A mass-and-spring structure obeys Mx¨=−Kx\mat{M}\ddot{\vb{x}} = -\mat{K}\vb{x}, and its natural frequencies come from Kv=ω2Mv\mat{K}\vb{v} = \omega^2\mat{M}\vb{v}, a symmetric problem. The lowest-frequency modes matter, not all of them: a typical case for shifted inverse iteration.
  • Loss curvature. The largest eigenvalue of a network’s Hessian determines the stable learning rate. The Hessian has d2d^2 entries with dd in the millions, but a Hessian-vector product costs one backpropagation: again use power iteration (see Hessian spectra in real networks).
  • Dynamical-system stability. xk+1=Axk\vb{x}_{k+1} = \mat{A}\vb{x}_k decays if the spectral radius is below 1. But if A\mat{A} is non-normal, computed eigenvalues may not mean what you think, and ∥Ak∥\norm{\mat{A}^k} can grow several orders of magnitude before decaying. The final part explains when to trust them.

The lesson follows the problem’s history: from power to inverse and Rayleigh quotient iteration, then QR with the ingredients that make it practical (Hessenberg reduction, shifts, deflation), its symmetric and SVD versions, and finally when a computed eigenvalue is reliable. You will implement everything from scratch and compare with LAPACK.

Why not the characteristic polynomial?

In conditioning and stability you saw Wilkinson’s polynomial: eigenvalues of diag⁡(1,…,20)\diag(1, \dots, 20) have condition number 1, yet roots of its characteristic polynomial can move in the third digit just from rounding coefficients to float64. Moving from matrix to coefficients chooses a severely ill-conditioned intermediate problem: an unstable algorithm even if each step is exact.

There is a second, deeper reason why no method can be “direct”.

Proof

Every monic polynomial p(z)=zn+an−1zn−1+⋯+a0p(z) = z^n + a_{n-1}z^{n-1} + \cdots + a_0 is, up to sign, the characteristic polynomial of its companion matrix, which has ones on the subdiagonal, −a0,…,−an−1-a_0, \dots, -a_{n-1} in the last column and zeros elsewhere. A finite eigenvalue algorithm applied to that matrix would give a formula for roots of pp using rational operations and radicals. For n≥5n \ge 5 no such formula exists for every polynomial: this is the Abel–Ruffini theorem (Abel, 1824).

∎

The design consequence is that every eigenvalue algorithm is iterative. Good ones converge so fast they seem direct, and divide work into two phases: a finite phase reducing A\mat{A} to a form with many zeros (Hessenberg or tridiagonal) in O(n3)\bigO(n^3) operations, and an iterative phase on that form costing O(n2)\bigO(n^2) per eigenvalue or less. What follows builds both.

Power iteration

The idea is the one you saw when applying A\mat{A} repeatedly: iterates align with the dominant eigenvector. An algorithm needs three decisions: normalization, eigenvalue estimation and stopping.

Normalization preserves direction and avoids overflow: without it, ∥Akx0∥\norm{\mat{A}^k\vb{x}_0} grows or decays like ∣λ1∣k\abs{\lambda_1}^k, and with ∣λ1∣=10\abs{\lambda_1} = 10 overflows float64 around iteration 308. The Rayleigh quotient is the best eigenvalue estimate for a given vector: it minimizes ∥Ax−ρx∥2\norm{\mat{A}\vb{x} - \rho\vb{x}}_2 over ρ\rho (the least-squares solution of xρ≈Ax\vb{x}\rho \approx \mat{A}\vb{x}).

InteractiveRace toward an eigenvector
  • power
  • inverse with σ
  • Rayleigh quotient
  • eigenvectors vi\vb{v}_i (vertices)
2.00
1.80
0.50
1.75
k = 30
Computing…
A=Qdiag⁡(λ1,λ2,λ3)Q⊤\mat{A} = \mat{Q}\diag(\lambda_1, \lambda_2, \lambda_3)\mat{Q}\T is symmetric, with eigenvalues you set and fixed eigenvectors vi\vb{v}_i. In the circle, the unit sphere viewed from direction (1,1,1)(1, 1, 1) of the eigenvector basis: each vi\vb{v}_i is a vertex and each method leaves a trail. The plot shows correct eigenvector digits, −log⁡10sin⁡∠(xk,v)-\log_{10}\sin\angle(\vb{x}_k, \vb{v}), versus iteration. First examine power iteration (blue): with λ2/λ1=0.9\lambda_2/\lambda_1 = 0.9 it gains about 0.050.05 digits per step. Move λ2\lambda_2 close to λ1\lambda_1 and then to −λ1-\lambda_1. The other curves are inverse iteration with shift σ\sigma and Rayleigh quotient iteration, studied next: move σ\sigma near any eigenvalue and watch the orange curve change destination and slope.

You prove the first part step by step in the final guided exercise. The second relies on a Rayleigh quotient property that reappears in the QR algorithm.

Proof

∥x∥2=1\norm{\vb{x}}_2 = 1. Expanding gives x⊤Ax=cos⁡2θ v⊤Av+sin⁡θcos⁡θ (w⊤Av+v⊤Aw)+sin⁡2θ w⊤Aw\vb{x}\T\mat{A}\vb{x} = \cos^2\theta\,\vb{v}\T\mat{A}\vb{v} + \sin\theta\cos\theta\,(\vb{w}\T\mat{A}\vb{v} + \vb{v}\T\mat{A}\vb{w}) + \sin^2\theta\,\vb{w}\T\mat{A}\vb{w}. The first summand of the cross term is w⊤(λv)=0\vb{w}\T(\lambda\vb{v}) = 0. The second also vanishes, but only by symmetry: v⊤Aw=(A⊤v)⊤w=(Av)⊤w=λ v⊤w=0\vb{v}\T\mat{A}\vb{w} = (\mat{A}\T\vb{v})\T\vb{w} = (\mat{A}\vb{v})\T\vb{w} = \lambda\,\vb{v}\T\vb{w} = 0. This leaves λcos⁡2θ+sin⁡2θ w⊤Aw=λ+sin⁡2θ (w⊤Aw−λ)\lambda\cos^2\theta + \sin^2\theta\,\vb{w}\T\mat{A}\vb{w} = \lambda + \sin^2\theta\,(\vb{w}\T\mat{A}\vb{w} - \lambda), and ∣w⊤Aw−λ∣≤2∥A∥2\abs{\vb{w}\T\mat{A}\vb{w} - \lambda} \le 2\norm{\mat{A}}_2.

∎

Vector error θ\theta gives eigenvalue error θ2\theta^2: a vector correct to 8 digits gives an eigenvalue correct to 16. For nonsymmetric matrices, v⊤Aw\vb{v}\T\mat{A}\vb{w} need not vanish and accuracy is only linear in θ\theta.

When to stop

Stopping when ρk\rho_k stops changing is tempting and dangerous: with a small gap, the change between iterates is much smaller than the error. The correct criterion is residual rk=Axk−ρkxk\vb{r}_k = \mat{A}\vb{x}_k - \rho_k\vb{x}_k, because of the backward error it certifies.

Proof

(A−rx⊤)x=Ax−r=ρx(\mat{A} - \vb{r}\vb{x}\T)\vb{x} = \mat{A}\vb{x} - \vb{r} = \rho\vb{x}, and the 2-norm of rank-one matrix rx⊤\vb{r}\vb{x}\T is ∥r∥2∥x∥2\norm{\vb{r}}_2\norm{\vb{x}}_2. For the second part, write x=∑icivi\vb{x} = \sum_i c_i\vb{v}_i in an orthonormal eigenvector basis: ∥r∥22=∑ici2(λi−ρ)2≥min⁡i(λi−ρ)2∑ici2\norm{\vb{r}}_2^2 = \sum_i c_i^2(\lambda_i - \rho)^2 \ge \min_i(\lambda_i - \rho)^2\sum_i c_i^2.

∎

So a good criterion is ∥rk∥2≤tol⋅∥A∥\norm{\vb{r}_k}_2 \le \text{tol}\cdot\norm{\mat{A}}: the computed pair is exact for a matrix at relative distance tol\text{tol} from yours. This is backward stability applied to an iteration: if data errors are that size, you cannot ask for more. How this translates to eigenvalue error depends on its sensitivity, studied at the end.

[ ]Power iteration from scratchBrowser
import numpy as np

def matriz_con_espectro(lams, seed=0):
    """A = Q diag(lams) Q^T con Q ortogonal aleatoria: simétrica con autovalores conocidos."""
    rng = np.random.default_rng(seed)
    Q, _ = np.linalg.qr(rng.normal(size=(len(lams), len(lams))))
    A = Q @ np.diag(lams) @ Q.T
    return (A + A.T) / 2, Q                # el producto en coma flotante no sale exactamente simétrico

def potencia(A, x0, tol=1e-12, max_iter=10_000):
    """Devuelve (rho, x, iteraciones). Para cuando ||A x - rho x|| <= tol * ||A||_1."""
    escala = np.linalg.norm(A, 1)
    x = x0 / np.linalg.norm(x0)
    for k in range(1, max_iter + 1):
        y = A @ x
        rho = x @ y                      # cociente de Rayleigh de x (||x|| = 1)
        if np.linalg.norm(y - rho * x) <= tol * escala:
            return rho, x, k
        x = y / np.linalg.norm(y)
    return rho, x, max_iter

lams = np.array([10.0, 9.0, 5.0, 3.0, 2.0, 1.0, 0.5, 0.1])
A, Q = matriz_con_espectro(lams)
v1 = Q[:, 0]
x0 = np.ones(8)
rho, x, k = potencia(A, x0)
print(f"potencia: {k} iteraciones, rho = {rho:.15f}, |rho - 10| = {abs(rho - 10):.1e}")

# tasas medidas: el vector converge como 0.9^k y el cociente de Rayleigh como 0.81^k
x = x0 / np.linalg.norm(x0)
seno, err_rho = [], []
for _ in range(150):
    x = A @ x
    x /= np.linalg.norm(x)
    seno.append(np.linalg.norm(x - (x @ v1) * v1))
    err_rho.append(abs(x @ A @ x - 10))
k = np.arange(1, 151)
tasa_v = np.exp(np.polyfit(k[20:120], np.log(seno[20:120]), 1)[0])
tasa_r = np.exp(np.polyfit(k[10:60], np.log(err_rho[10:60]), 1)[0])
print(f"tasa del vector: {tasa_v:.4f}  (|l2/l1| = {9/10})")
print(f"tasa del autovalor: {tasa_r:.4f}  (|l2/l1|^2 = {(9/10)**2:.2f})")
print(f"iteraciones para reducir el error del vector 1e6: {np.ceil(np.log(1e-6) / np.log(0.9)):.0f}")

The measured vector rate is 0.90020.9002 and eigenvalue rate 0.81950.8195: the square of 0.90.9, as predicted. With tolerance 10−1210^{-12} relative to ∥A∥1\norm{\mat{A}}_1, 251 iterations are needed, although the eigenvalue was correct to 15 digits much earlier: the residual measures the vector, which converges at half the speed. This is the price of gap ∣λ2/λ1∣=0.9\abs{\lambda_2/\lambda_1} = 0.9. For huge sparse matrices (PageRank, Hessians), this slowness is accepted because each iteration is cheap; otherwise there is something much better.

Inverse iteration and the Rayleigh quotient

The eigenvalues of (A−σI)−1(\mat{A} - \sigma\mat{I})\inv are 1/(λi−σ)1/(\lambda_i - \sigma), with the same eigenvectors. The dominant one corresponds to the λJ\lambda_J closest to σ\sigma, and power iteration on that matrix converges to vJ\vb{v}_J with factor

∣λJ−σ∣∣λK−σ∣,λK=el segundo autovalor maˊs cercano a σ.\frac{\abs{\lambda_J - \sigma}}{\abs{\lambda_K - \sigma}}, \qquad \lambda_K = \text{el segundo autovalor más cercano a } \sigma.

This is shifted inverse iteration and its Rayleigh quotient version. With a good σ\sigma the factor can be arbitrarily small: with eigenvalues 1,3,71, 3, 7 and σ=2.9\sigma = 2.9 it equals 0.1/1.9≈0.0530.1/1.9 \approx 0.053, and each step gains 1.31.3 digits. Never invert the matrix: factor A−σI=P⊤LU\mat{A} - \sigma\mat{I} = \mat{P}\T\mat{L}\mat{U} once with partial pivoting, and each iteration solves two triangular systems in O(n2)\bigO(n^2).

What if the shift is updated each step with the best available estimate? That estimate is the Rayleigh quotient.

The argument fits in two lines. By the previous theorem, ∣ρk−λJ∣=O(θk2)\abs{\rho_k - \lambda_J} = \bigO(\theta_k^2). One inverse iteration step with shift ρk\rho_k multiplies the angle’s tangent by a factor of order ∣λJ−ρk∣/∣λK−ρk∣=O(θk2)\abs{\lambda_J - \rho_k}/\abs{\lambda_K - \rho_k} = \bigO(\theta_k^2), so θk+1=O(θk⋅θk2)\theta_{k+1} = \bigO(\theta_k\cdot\theta_k^2). Without symmetry, ∣ρk−λJ∣=O(θk)\abs{\rho_k - \lambda_J} = \bigO(\theta_k), leaving θk+1=O(θk2)\theta_{k+1} = \bigO(\theta_k^2). Ostrowski proved this in papers from 1958 and 1959; full symmetric-case analysis is in chapter 4 of Parlett.

“Cubic” means correct digits triple at each step. In float64 this looks like a jump from about 3 digits to 10 and then to rounding. To really see it needs more precision: mpmath uses whatever you request.

[ ]Digits triple: Rayleigh quotient iteration with 150 digitsBrowser
import numpy as np
import mpmath as mp

A, Q = matriz_con_espectro(np.array([10.0, 9.0, 5.0, 3.0, 2.0, 1.0, 0.5, 0.1]))
mp.mp.dps = 150                                    # 150 cifras decimales
Am = mp.matrix(A.tolist())
x = mp.matrix([1] * 8)
x = x / mp.norm(x)
print(" k   rho_k                    ||A x - rho x||   cifras")
for k in range(6):
    rho = (x.T * Am * x)[0]
    r = mp.norm(Am * x - rho * x)
    print(f"{k:2d}   {mp.nstr(rho, 20):24s} {mp.nstr(r, 3):>12s}   {float(-mp.log10(r)):6.1f}")
    y = mp.lu_solve(Am - rho * mp.eye(8), x)
    x = y / mp.norm(y)

Starting from the all-ones vector, residuals pass through 2.42.4, 0.360.36, 6.4×10−46.4\times 10^{-4}, 6.3×10−116.3\times 10^{-11} and 5.4×10−325.4\times 10^{-32}: once convergence takes hold, digits progress as 3.2→10.2→31.3→943.2 \to 10.2 \to 31.3 \to 94, tripling each step. A detail matters: matriz_con_espectro symmetrizes A\mat{A} using (A + A.T) / 2, because floating-point product QΛQ⊤\mat{Q}\mat{\Lambda}\mat{Q}\T is not exactly symmetric. Without that line, asymmetry 10−1610^{-16} suffices to make convergence quadratic, as for a nonsymmetric matrix, after about 30 digits. Notice which eigenvalue it reaches: 22, not dominant 1010, nor the one nearest the initial Rayleigh quotient ρ0=2.66\rho_0 = 2.66, which is 33. The destination depends on the whole starting vector, not just ρ0\rho_0. Rayleigh quotient iteration is extremely fast, but you do not choose its destination. In the earlier race, the pink curve reaches rounding in three or four steps, but check which vertex it approaches. In practice it is combined with something controlling the process globally, exactly what QR does.

From unshifted QR to the practical algorithm

The preceding iterations compute one eigenvector at a time. To find all simultaneously, naturally iterate a block of vectors and reorthogonalize at each step, so the first converges to v1\vb{v}_1, the second to the next orthogonal complement, and so on. This is simultaneous iteration, whose efficient form is one of the twentieth century’s most important algorithms.

Simultaneous iteration is the QR algorithm

Since Rk=Qk⊤Ak\mat{R}_k = \mat{Q}_k\T\mat{A}_k, each step is an orthogonal similarity: Ak+1=Qk⊤AkQk\mat{A}_{k+1} = \mat{Q}_k\T\mat{A}_k\mat{Q}_k. Every Ak\mat{A}_k has the eigenvalues of A\mat{A}. What it computes is surprising.

Proof

The second equality composes the similarities. For the first, use induction: for k=1k = 1 it is A=Q0R0\mat{A} = \mat{Q}_0\mat{R}_0. If true for kk, Ak+1=A Q‾kR‾k=Q‾kAkR‾k=Q‾kQkRkR‾k=Q‾k+1R‾k+1\mat{A}^{k+1} = \mat{A}\,\underline{\mat{Q}}_k\underline{\mat{R}}_k = \underline{\mat{Q}}_k\mat{A}_k\underline{\mat{R}}_k = \underline{\mat{Q}}_k\mat{Q}_k\mat{R}_k\underline{\mat{R}}_k = \underline{\mat{Q}}_{k+1}\underline{\mat{R}}_{k+1}, using AQ‾k=Q‾kAk\mat{A}\underline{\mat{Q}}_k = \underline{\mat{Q}}_k\mat{A}_k.

∎

Thus the first column of Q‾k\underline{\mat{Q}}_k performs power iteration, and the first jj generate Akspan⁡{e1,…,ej}\mat{A}^k\spn\{\vb{e}_1, \dots, \vb{e}_j\}, converging to the invariant subspace of the jj dominant eigenvalues. If magnitudes are distinct, ∣λ1∣>⋯>∣λn∣\abs{\lambda_1} > \cdots > \abs{\lambda_n} (and e1,…,ej\vb{e}_1, \dots, \vb{e}_j are not deficient with respect to those subspaces, generically true), Ak\mat{A}_k approaches an upper triangular matrix with eigenvalues on its diagonal, the Schur form, and entry (j+1,j)(j + 1, j) decays as ∣λj+1/λj∣k\abs{\lambda_{j+1}/\lambda_j}^k. Linear convergence with the same ratios as power iteration: two more ideas are needed.

Hessenberg reduction

One QR step on a dense matrix costs O(n3)\bigO(n^3), and order nn steps are needed: O(n4)\bigO(n^4). The first idea is to prepare the matrix.

Why not go straight to triangular? Abel–Ruffini makes it impossible. If the first reflection tried to zero the entire first column below the diagonal (as in QR), applying it on the right would mix the first column with the others and destroy the zeros. Starting at row 2, right multiplication leaves column 1 alone, so zeros survive. Cost is about 103n3\tfrac{10}{3}n^3 operations; if A\mat{A} is symmetric, so is H\mat{H}, hence it is tridiagonal, and exploiting symmetry reduces cost to 43n3\tfrac{4}{3}n^3 (Trefethen and Bau, lecture 26).

The reduction pays off because it is preserved: if H\mat{H} is Hessenberg and H−μI=QR\mat{H} - \mu\mat{I} = \mat{Q}\mat{R}, then RQ+μI\mat{R}\mat{Q} + \mu\mat{I} is also Hessenberg. If R\mat{R} is invertible, Q=(H−μI)R−1\mat{Q} = (\mat{H} - \mu\mat{I})\mat{R}\inv is Hessenberg times upper triangular, which is Hessenberg, and RQ\mat{R}\mat{Q} is upper triangular times Hessenberg, again Hessenberg (the singular case follows by continuity or construction with rotations). Hessenberg QR uses n−1n - 1 Givens rotations, one per subdiagonal entry, and a step costs O(n2)\bigO(n^2); for tridiagonal matrices, O(n)\bigO(n).

Shifts

The second idea comes from inverse iteration. A QR step with shift μ\mu is

Ak−μkI=QkRk,Ak+1=RkQk+μkI=Qk⊤AkQk,\mat{A}_k - \mu_k\mat{I} = \mat{Q}_k\mat{R}_k, \qquad \mat{A}_{k+1} = \mat{R}_k\mat{Q}_k + \mu_k\mat{I} = \mat{Q}_k\T\mat{A}_k\mat{Q}_k,

again an orthogonal similarity. Look at the last column of Qk\mat{Q}_k. From Ak−μkI=QkRk\mat{A}_k - \mu_k\mat{I} = \mat{Q}_k\mat{R}_k follows (Ak−μkI)−T=QkRk−T(\mat{A}_k - \mu_k\mat{I})^{-\mathsf{T}} = \mat{Q}_k\mat{R}_k^{-\mathsf{T}}, and since Rk−T\mat{R}_k^{-\mathsf{T}} is lower triangular, its last column is en/rnn\vb{e}_n/r_{nn}:

(Ak−μkI)−Ten=1rnn Qken.(\mat{A}_k - \mu_k\mat{I})^{-\mathsf{T}}\vb{e}_n = \frac{1}{r_{nn}}\,\mat{Q}_k\vb{e}_n.

The last column of Qk\mat{Q}_k is an inverse-iteration step with shift μk\mu_k on Ak⊤\mat{A}_k\T, starting at en\vb{e}_n. If μk\mu_k is near an eigenvalue, the last row of Ak+1\mat{A}_{k+1} rapidly approaches (0,…,0,λ)(0, \dots, 0, \lambda): entry an,n−1a_{n,n-1} vanishes and anna_{nn} is an eigenvalue. With Rayleigh shift μk=(Ak)nn\mu_k = (\mat{A}_k)_{nn}, the Rayleigh quotient of en\vb{e}_n, QR performs Rayleigh quotient iteration in its last row: quadratic convergence in general and cubic if A\mat{A} is symmetric.

When ∣an,n−1∣\abs{a_{n,n-1}} falls below u(∣an−1,n−1∣+∣ann∣)u(\abs{a_{n-1,n-1}} + \abs{a_{nn}}), set it to zero: this is deflation. The matrix is block triangular, anna_{nn} is an eigenvalue and the algorithm continues with the upper (n−1)×(n−1)(n-1)\times(n-1) submatrix, which keeps shrinking. If an intermediate subdiagonal entry becomes negligible, the problem splits into two independent ones.

Wilkinson’s shift

Rayleigh’s shift can fail. With A=[0110]\mat{A} = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, μ=a22=0\mu = a_{22} = 0, A\mat{A} is already orthogonal, its QR is A=A⋅I\mat{A} = \mat{A}\cdot\mat{I} and RQ=A\mat{R}\mat{Q} = \mat{A}: nothing ever changes. Eigenvalues ±1\pm 1 are equally distant from μ=0\mu = 0 and underlying inverse iteration has no preference. Wilkinson’s solution looks at the final 2×22\times 2 block, [abbc]\begin{bmatrix} a & b \\ b & c \end{bmatrix}, and takes as μ\mu its eigenvalue nearest cc:

μ=c−sign⁡(δ) b2∣δ∣+δ2+b2,δ=a−c2,\mu = c - \frac{\operatorname{sign}(\delta)\,b^2}{\abs{\delta} + \sqrt{\delta^2 + b^2}}, \qquad \delta = \frac{a - c}{2},

written without the catastrophic subtraction of the quadratic formula (with δ=0\delta = 0 either sign may be chosen). Wilkinson proved in 1968 that with this shift QR on a symmetric tridiagonal matrix always converges, and in practice final convergence is cubic.

InteractiveThe QR algorithm as a heatmap
11e−41e−81e−121e−16051015QR steps after reduction|t(k+1, k)|
∣tij∣|t_{ij}|:≥ 110⁻¹10⁻³10⁻⁶10⁻⁹10⁻¹²< 10⁻¹²0 exact
  • active block and its last subdiagonal entry
  • other subdiagonal entries
  • deflation (isolated eigenvalue)
Matrix
Shift
step 18
Computing…
Log-scale heatmap of ∣tij∣\abs{t_{ij}} for a symmetric 8×88\times 8 matrix through the algorithm. Frame 0: the original dense matrix. Frame 1: tridiagonal after Householder reduction. Then one QR step per frame on the active block (pink outline), deflating when a subdiagonal entry falls below relative 10−1410^{-14}. The plot shows seven subdiagonal entries on a log scale; pink is the active block's last. Compare three shifts on a matrix with spectrum 8,6.5,…,0.58, 6.5, \dots, 0.5: without a shift, straight lines of slope log⁡∣λj+1/λj∣\log\abs{\lambda_{j+1}/\lambda_j}; with Rayleigh or Wilkinson, drops of 3 to 10 digits and bottom-up deflations. Then switch to spectrum ±σi\pm\sigma_i, a tridiagonal matrix with zero diagonal: which shift survives?

In the interactive, the matrix with spectrum 8,6.5,5,4,3,2,1.2,0.58, 6.5, 5, 4, 3, 2, 1.2, 0.5 needs 182 unshifted steps, 21 with Rayleigh and 18 with Wilkinson, just over two per eigenvalue. Subdiagonal curves show why: unshifted they fall in straight lines, while with Wilkinson the active block’s last goes from 1.8×10−11.8\times 10^{-1} to 5.2×10−45.2\times 10^{-4} and 1.3×10−111.3\times 10^{-11}, tripling digits, and deflates next step. The zero-diagonal matrix has eigenvalues in equal-magnitude pairs ±σi\pm\sigma_i. Without a shift, subdiagonal entries separating different pairs decay linearly, but those within each pair do not move, and final block 2×22\times 2, [0bb0]\begin{bmatrix} 0 & b \\ b & 0 \end{bmatrix} with b≈0.54b \approx 0.54, remains forever. Rayleigh behaves identically because the diagonal stays zero at every step and the shift is always 0: the earlier 2×22\times 2 writ large. Wilkinson finishes in 18 steps. This matrix returns in SVD computation.

Francis and the implicit double shift

A real nonsymmetric matrix can have complex eigenvalues, which no real shift isolates: an 2×22\times 2 block with a conjugate pair never vanishes. Complex shifts and arithmetic would double cost and lose real structure. J. G. F. Francis’s solution (1961), independently developed at the same time by Vera Kublanovskaya, takes two consecutive steps with μ\mu and μˉ\bar\mu, eigenvalues of the final 2×22\times 2 block. Together they are equivalent to factoring

M=(H−μI)(H−μˉI)=H2−sH+tI,s=2Re⁡μ,t=∣μ∣2,\mat{M} = (\mat{H} - \mu\mat{I})(\mat{H} - \bar\mu\mat{I}) = \mat{H}^2 - s\mat{H} + t\mat{I}, \qquad s = 2\operatorname{Re}\mu, \quad t = \abs{\mu}^2,

which is real. Forming M\mat{M} would cost O(n3)\bigO(n^3), but is unnecessary thanks to the implicit Q theorem: if Q⊤HQ\mat{Q}\T\mat{H}\mat{Q} is unreduced Hessenberg (no subdiagonal zeros), Q\mat{Q} is determined up to signs by its first column. Francis computes only the first column of M\mat{M}, with three nonzeros, applies reflection 3×33\times 3 taking it to e1\vb{e}_1 (creating a “bulge” outside Hessenberg form), and chases the bulge downward with small reflections until Hessenberg form returns. The theorem gives the same result as an explicit double step in about 10n210n^2 operations using real arithmetic. The limit is real Schur form: nearly triangular, with 1×11\times 1 blocks for real eigenvalues and 2×22\times 2 blocks for complex pairs.

Modern LAPACK goes further: hseqr chains many small shifts at once to use level-3 BLAS and seeks deflations in a wide window at the matrix end (“aggressive early deflation”, Braman, Byers and Mathias, 2002). Francis’s idea remains the core. Golub and Van Loan count about 10n310n^3 operations for eigenvalues and 25n325n^3 if Schur vectors are also needed.

Implementation from scratch

The version below uses complex arithmetic with one Wilkinson shift (the eigenvalue of the final 2×22\times 2 nearest the corner, potentially complex): simpler than Francis’s double step and converging the same way, but losing real structure at a constant-factor cost. Hessenberg reduction follows the definition, with Householder reflections applied on both sides.

[ ]Householder Hessenberg reductionBrowser
import numpy as np
import scipy.linalg as sla

def hessenberg(A):
    """H = Q^H A Q de Hessenberg superior con reflexiones de Householder. Devuelve (H, Q)."""
    H = np.array(A, dtype=complex if np.iscomplexobj(A) else float)
    n = H.shape[0]
    Q = np.eye(n, dtype=H.dtype)
    for k in range(n - 2):
        x = H[k + 1:, k]
        nx = np.linalg.norm(x)
        if nx == 0:
            continue
        v = x.copy()
        fase = x[0] / abs(x[0]) if x[0] != 0 else 1.0
        v[0] += fase * nx                       # sin cancelación: mismo signo (fase) que x[0]
        v /= np.linalg.norm(v)
        H[k + 1:, k:] -= 2 * np.outer(v, v.conj() @ H[k + 1:, k:])    # por la izquierda
        H[:, k + 1:] -= 2 * np.outer(H[:, k + 1:] @ v, v.conj())      # por la derecha
        Q[:, k + 1:] -= 2 * np.outer(Q[:, k + 1:] @ v, v.conj())
        H[k + 2:, k] = 0                        # ceros exactos donde deben estar
    return H, Q

rng = np.random.default_rng(1)
A = rng.normal(size=(6, 6))
H, Q = hessenberg(A)
print("ceros bajo la subdiagonal:", np.allclose(np.tril(H, -2), 0))
print("Q ortogonal:              ", np.allclose(Q.T @ Q, np.eye(6)))
print("Q H Q^T = A:              ", np.allclose(Q @ H @ Q.T, A))
print("mismos autovalores:        ", np.allclose(np.sort_complex(np.linalg.eigvals(H)), np.sort_complex(np.linalg.eigvals(A))))
S = A + A.T
T, _ = hessenberg(S)
print("simétrica -> tridiagonal:  ", np.allclose(np.triu(T, 2), 0) and np.allclose(np.tril(T, -2), 0))
print("coincide con scipy (|h_ij|):", np.allclose(np.abs(H), np.abs(sla.hessenberg(A))))

Comparison with scipy.linalg.hessenberg uses absolute values: both use Householder reflections, but SciPy’s (LAPACK gehrd) may choose another sign, and Hessenberg form is determined only up to signs (the implicit Q theorem). Now the QR algorithm.

[ ]QR with Wilkinson shift and deflationBrowser
import numpy as np
import scipy.linalg as sla
import time

def desplazamiento_wilkinson(B):
    """Autovalor de la 2x2 final de B más cercano a la esquina B[-1, -1] (puede ser complejo)."""
    a, b, c, d = B[-2, -2], B[-2, -1], B[-1, -2], B[-1, -1]
    media, det = (a + d) / 2, a * d - b * c
    disc = np.sqrt(complex(media * media - det))
    l1, l2 = media + disc, media - disc
    return l1 if abs(l1 - d) <= abs(l2 - d) else l2

def paso_qr(H, mu):
    """Un paso QR con desplazamiento sobre la Hessenberg H (in situ) con rotaciones de Givens."""
    n = H.shape[0]
    H[np.diag_indices(n)] -= mu
    G = []
    for k in range(n - 1):                      # H - mu I = Q R: anula la subdiagonal
        a, b = H[k, k], H[k + 1, k]
        r = np.hypot(abs(a), abs(b))
        c, s = (a / r, b / r) if r > 0 else (1.0, 0.0)
        g = np.array([[np.conj(c), np.conj(s)], [-s, c]])
        H[k:k + 2, k:] = g @ H[k:k + 2, k:]
        G.append(g)
    for k, g in enumerate(G):                   # R Q: las mismas rotaciones por la derecha
        H[:k + 2, k:k + 2] = H[:k + 2, k:k + 2] @ g.conj().T
    H[np.diag_indices(n)] += mu

def qr_autovalores(A, tol=np.finfo(float).eps, max_pasos=None):
    """Todos los autovalores de A con Hessenberg + QR con desplazamiento de Wilkinson + deflación."""
    H, _ = hessenberg(np.asarray(A, dtype=complex))
    n = H.shape[0]
    max_pasos = max_pasos or 30 * n
    lam = np.zeros(n, dtype=complex)
    hi, pasos = n - 1, 0
    while hi > 0:
        # deflación en la esquina
        if abs(H[hi, hi - 1]) <= tol * (abs(H[hi, hi]) + abs(H[hi - 1, hi - 1])):
            H[hi, hi - 1] = 0
            lam[hi] = H[hi, hi]
            hi -= 1
            continue
        # bloque activo [lo, hi]: hasta el primer elemento subdiagonal despreciable
        lo = hi - 1
        while lo > 0 and abs(H[lo, lo - 1]) > tol * (abs(H[lo, lo]) + abs(H[lo - 1, lo - 1])):
            lo -= 1
        if lo > 0:
            H[lo, lo - 1] = 0
        B = H[lo:hi + 1, lo:hi + 1].copy()
        paso_qr(B, desplazamiento_wilkinson(B))
        H[lo:hi + 1, lo:hi + 1] = B
        pasos += 1
        if pasos > max_pasos:
            raise RuntimeError("el algoritmo QR no converge")
    lam[0] = H[0, 0]
    return lam, pasos

rng = np.random.default_rng(1)
for n in (10, 40, 80):
    S = rng.normal(size=(n, n)); S = S + S.T          # simétrica
    G = rng.normal(size=(n, n))                       # general: pares complejos
    lam_s, p_s = qr_autovalores(S)
    lam_g, p_g = qr_autovalores(G)
    err_s = np.max(np.abs(np.sort(lam_s.real) - sla.eigh(S, eigvals_only=True))) / np.linalg.norm(S, 2)
    ref = sla.eigvals(G)
    err_g = max(np.min(np.abs(ref - l)) for l in lam_g) / np.linalg.norm(G, 2)
    print(f"n = {n:3d}   simétrica: {p_s:4d} pasos ({p_s / n:.2f} por autovalor), error {err_s:.1e}"
          f"   general: {p_g:4d} pasos ({p_g / n:.2f}), error {err_g:.1e}")

n = 80
S = rng.normal(size=(n, n)); S = S + S.T
t0 = time.perf_counter(); qr_autovalores(S); t_nuestro = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(20): sla.eig(S)
t_eig = (time.perf_counter() - t0) / 20
t0 = time.perf_counter()
for _ in range(20): sla.eigh(S, eigvals_only=True)
t_eigh = (time.perf_counter() - t0) / 20
print(f"\nn = 80: nuestro QR / scipy eig = {t_nuestro / t_eig:.0f}   scipy eig / eigvalsh = {t_eig / t_eigh:.1f}")

Errors are of order 10−1510^{-15} relative to ∥A∥2\norm{\mat{A}}_2, as expected from a backward-stable algorithm, and step counts confirm theory: about 2 per eigenvalue for symmetric matrices (cubic convergence) and 3 for general ones (quadratic). Our version is tens of times slower than scipy.linalg.eig (about 30 in the cell run, though the ratio varies by machine) because each rotation is a Python call with 2×22\times 2 matrices; the algorithm is the same, and in a compiled language the loop costs O(n2)\bigO(n^2) per step as theory promises. The last line anticipates the next section: for the same symmetric matrix, eig is several times slower than eigh for eigenvalues only.

The symmetric case

When A=A⊤\mat{A} = \mat{A}\T everything improves at once. The spectral theorem guarantees real eigenvalues and an orthonormal eigenvector basis; reduction gives a tridiagonal in 43n3\tfrac{4}{3}n^3 operations; and sensitivity is as low as possible.

Since LAPACK’s symmetric algorithms are backward stable with symmetric perturbation ∥E∥2≈u∥A∥2\norm{\mat{E}}_2 \approx u\norm{\mat{A}}_2, each computed eigenvalue has absolute error of order u∥A∥2u\norm{\mat{A}}_2, independent of anything else. Eigenvectors are different: the Davis–Kahan sin⁡θ\sin\theta theorem bounds the angle between exact and computed eigenvectors by ∥E∥2/hueco\norm{\mat{E}}_2/\text{hueco}, where the gap is the distance from λi\lambda_i to the rest of the spectrum. With nearly repeated eigenvalues individual eigenvectors are poorly determined, even when their joint subspace is well determined.

For the tridiagonal, LAPACK offers several symmetric methods:

MethodRoutineIdeaTridiagonal cost
Implicit QRsteqrprevious section’s method with WilkinsonO(n2)\bigO(n^2) eigenvalues; O(n3)\bigO(n^3) with vectors
Divide and conquerstedcsplits the tridiagonal with a rank-one correction (Cuppen, 1981) and merges spectra by solving a secular equationO(n3)\bigO(n^3) with vectors, much less in practice due to deflation
Bisection and inverse iterationstebz, steincounts eigenvalues below xx using Sylvester’s inertia law and refines with inverse iterationO(nk)\bigO(nk) for kk eigenvalues, plus reorthogonalizing vectors for clustered eigenvalues
MRRRstemrrelatively robust representations: kk orthogonal eigenvectors without reorthogonalization (Dhillon and Parlett, 2004)O(nk)\bigO(nk)

np.linalg.eigh calls syevd (divide and conquer), and scipy.linalg.eigh defaults to syevr (MRRR), with argument driver to choose another and subset_by_index or subset_by_value to request a subset. In both cases, dense matrices are dominated by tridiagonalization and transformation back to the original basis, not the tridiagonal phase.

Why not use eig, which accepts symmetric matrices too? Because eig does not know the matrix is symmetric: it reduces to Hessenberg form (which would be tridiagonal in exact arithmetic, but is not exactly symmetric in floating point) and applies the general algorithm.

[ ]eig versus eigh for a rank-deficient covarianceBrowser
import numpy as np
import scipy.linalg as sla
import time

rng = np.random.default_rng(0)
X = rng.normal(size=(30, 50))              # 30 muestras de 50 variables: más variables que muestras
C = np.cov(X, rowvar=False)                # 50x50, simétrica, semidefinida positiva, de rango 29

w, V = np.linalg.eig(C)
print("eig : dtype", w.dtype, "| autovalores con parte imaginaria no nula:", np.sum(w.imag != 0),
      "| max |Im| =", f"{np.abs(w.imag).max():.1e}")
print("      ||V^T V - I|| =", f"{np.linalg.norm(V.conj().T @ V - np.eye(50)):.2f}",
      "| autovalores negativos:", np.sum(w.real < 0))
wh, Vh = np.linalg.eigh(C)
print("eigh: dtype", wh.dtype, "| ordenados:", bool(np.all(np.diff(wh) >= 0)),
      "| ||V^T V - I|| =", f"{np.linalg.norm(Vh.T @ Vh - np.eye(50)):.1e}",
      "| mínimo:", f"{wh[0]:.1e}")

# coste: eig frente a eigh y eigvalsh
S = rng.normal(size=(200, 200)); S = S + S.T
def mide(f, rep=3):
    t0 = time.perf_counter()
    for _ in range(rep): f()
    return (time.perf_counter() - t0) / rep
t_eig = mide(lambda: np.linalg.eig(S))
t_eigh = mide(lambda: np.linalg.eigh(S))
t_eigvalsh = mide(lambda: np.linalg.eigvalsh(S))
print(f"\nn = 200: eig / eigh = {t_eig / t_eigh:.1f}   eig / eigvalsh = {t_eig / t_eigvalsh:.1f}")
# solo los 3 mayores con scipy
top = sla.eigh(S, subset_by_index=[197, 199], eigvals_only=True)
print("los 3 mayores (subset_by_index):", np.round(top, 6), " coinciden:", np.allclose(top, np.linalg.eigvalsh(S)[-3:]))

With 30 samples of 50 variables, covariance has rank 29 and a zero eigenvalue of multiplicity 21. Here eig returns a complex array, with several imaginary parts of order 10−1610^{-16} among the zero eigenvalues, and nonorthogonal eigenvectors: any basis works in a repeated eigenspace, and eig has no reason to choose an orthonormal one. eigh returns ordered real eigenvalues and a basis orthonormal to rounding. Both return some slightly negative eigenvalues (the smallest from eigh is −1.9×10−15-1.9\times 10^{-15}): this is rounding error u∥C∥u\norm{\mat{C}} guaranteed by Weyl, and why clipping to zero before taking roots is useful. eigh is also several times faster.

SVD on a computer

The SVD A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T is tied to the symmetric problem: σi2\sigma_i^2 are eigenvalues of A⊤A\mat{A}\T\mat{A} and columns of V\mat{V} their eigenvectors. The obvious recipe is to form A⊤A\mat{A}\T\mat{A}, call eigh and take square roots. This is a mistake; the interactive shows why.

InteractiveThe AᵀA floor
  • true σᵢ
  • SVD of A
  • √λᵢ(AᵀA)
12.0
Computing…
A=Udiag⁡(σ1,…,σ10)V⊤∈R20×10\mat{A} = \mat{U}\diag(\sigma_1, \dots, \sigma_{10})\mat{V}\T \in \R^{20\times 10} with random orthogonal U,V\mat{U}, \mat{V} and σi\sigma_i logarithmically spaced between 1 and 10−p10^{-p}. Here float64 computes the SVD of A\mat{A} (one-sided Jacobi, a backward-stable algorithm) and square roots of eigenvalues of the formed A⊤A\mat{A}\T\mat{A} (cyclic Jacobi, exact for that matrix up to rounding). Increase pp: where does the red curve leave the true one, and what happens to eigenvalues of A⊤A\mat{A}\T\mat{A} below that point?

The red curve tracks truth until σi≈10−8\sigma_i \approx 10^{-8}, then departs: below it values are of order 10−810^{-8} unrelated to the truth, or negative eigenvalues have no real square root. Error accounting explains this. Forming A⊤A\mat{A}\T\mat{A} in floating point incurs symmetric error F\mat{F} with ∥F∥2\norm{\mat{F}}_2 of order u∥A∥22=uσ12u\norm{\mat{A}}_2^2 = u\sigma_1^2 (times a dimension-dependent constant), and Weyl says each eigenvalue σi2\sigma_i^2 moves by up to ∥F∥2\norm{\mat{F}}_2. Relative error in σi2\sigma_i^2 is then of order u(σ1/σi)2u(\sigma_1/\sigma_i)^2 and in σi\sigma_i half that. Once σi2≲uσ12\sigma_i^2 \lesssim u\sigma_1^2, meaning σi≲u σ1≈10−8σ1\sigma_i \lesssim \sqrt{u}\,\sigma_1 \approx 10^{-8}\sigma_1, no digits survive. This is the same loss as for normal equations: squaring the condition number. A backward-stable SVD instead gives exact singular values of A+E\mat{A} + \mat{E} with ∥E∥2≈u∥A∥2\norm{\mat{E}}_2 \approx u\norm{\mat{A}}_2, and by Weyl’s singular-value version, ∣σ^i−σi∣≤∥E∥2\abs{\hat\sigma_i - \sigma_i} \le \norm{\mat{E}}_2: absolute error uσ1u\sigma_1, not u σ1\sqrt{u}\,\sigma_1.

Golub–Kahan bidiagonalization

The correct way to compute SVD imitates the symmetric case without forming A⊤A\mat{A}\T\mat{A}. Phase 1 (Golub and Kahan, 1965): alternating Householder reflections on left and right reduce A∈Rm×n\mat{A} \in \R^{m\times n} to upper bidiagonal form,

UB⊤AVB=B=[d1e1d2⋱⋱en−1dn],\mat{U}_B\T\mat{A}\mat{V}_B = \mat{B} = \begin{bmatrix} d_1 & e_1 & & \\ & d_2 & \ddots & \\ & & \ddots & e_{n-1} \\ & & & d_n \end{bmatrix},

in about 4mn2−43n34mn^2 - \tfrac{4}{3}n^3 operations. Left reflections zero column kk below the diagonal; right reflections zero row kk starting at the second superdiagonal. The right side may start one position later because similarity is unnecessary: UB\mat{U}_B and VB\mat{V}_B differ. If m≫nm \gg n, it is cheaper first to compute QR, A=QR\mat{A} = \mat{Q}\mat{R}, then bidiagonalize square R\mat{R} (Lawson–Hanson–Chan bidiagonalization).

Phase 2: singular values of B\mat{B}. The zero-diagonal tridiagonal from the heatmap returns. Symmetric matrix [0B⊤B0]\begin{bmatrix} \mat{0} & \mat{B}\T \\ \mat{B} & \mat{0} \end{bmatrix} of size 2n2n has eigenvalues ±σi\pm\sigma_i, and reordering rows and columns as 1,n+1,2,n+2,…1, n+1, 2, n+2, \dots turns it into the tridiagonal

TGK=tridiag⁡(0; d1,e1,d2,e2,…,en−1,dn),\mat{T}_{GK} = \operatorname{tridiag}\big(0;\ d_1, e_1, d_2, e_2, \dots, e_{n-1}, d_n\big),

with zero diagonal. SVD is therefore a symmetric tridiagonal problem, and the previous section’s methods adapt to work directly on B\mat{B}: Golub and Reinsch’s implicit QR (1970), equivalent to symmetric QR applied to B⊤B\mat{B}\T\mat{B} without forming it; Demmel and Kahan’s variant (1990), computing every singular value of a bidiagonal matrix with small relative error, even tiny ones; Fernando and Parlett’s dqds algorithm (1994) for values alone; and divide and conquer (bdsdc). np.linalg.svd and scipy.linalg.svd default to gesdd, the divide-and-conquer version; scipy.linalg.svd(..., lapack_driver="gesvd") uses QR, slower and sometimes more robust.

[ ]Golub–Kahan from scratch and AᵀA information lossBrowser
import numpy as np

def householder(x):
    """v unitario con (I - 2 v v^T) x = -sign(x0) ||x|| e1."""
    v = x.astype(float).copy()
    v[0] += np.copysign(np.linalg.norm(x), x[0])
    nv = np.linalg.norm(v)
    return v / nv if nv > 0 else v

def bidiagonalizar(A):
    """B = U^T A V bidiagonal superior (n x n) con reflexiones alternas. Solo devuelve B."""
    B = np.array(A, dtype=float)
    m, n = B.shape
    for k in range(n):
        v = householder(B[k:, k])                       # columna k: ceros bajo la diagonal
        B[k:, k:] -= 2 * np.outer(v, v @ B[k:, k:])
        if k < n - 2:
            v = householder(B[k, k + 1:])               # fila k: ceros desde la 2.ª superdiagonal
            B[k:, k + 1:] -= 2 * np.outer(B[k:, k + 1:] @ v, v)
    return B[:n, :n]

rng = np.random.default_rng(0)
m, n = 60, 12
U, _ = np.linalg.qr(rng.normal(size=(m, n)))
V, _ = np.linalg.qr(rng.normal(size=(n, n)))
s = np.logspace(0, -14, n)                              # sigma_1 = 1, ..., sigma_12 = 1e-14
A = U @ np.diag(s) @ V.T

B = bidiagonalizar(A)
print("bidiagonal:", np.allclose(np.tril(B, -1), 0, atol=1e-15) and np.allclose(np.triu(B, 2), 0, atol=1e-15))
d, e = np.diag(B), np.diag(B, 1)
off = np.empty(2 * n - 1); off[0::2] = d; off[1::2] = e
T = np.diag(off, 1) + np.diag(off, -1)                  # Golub-Kahan: diagonal nula
w = np.linalg.eigvalsh(T)
print("autovalores de T_GK = ±sigma:", np.allclose(np.sort(w[w > 0])[::-1], np.linalg.svd(B, compute_uv=False)))

s_svd = np.linalg.svd(A, compute_uv=False)
lam = np.linalg.eigvalsh(A.T @ A)[::-1]
s_ata = np.sqrt(np.clip(lam, 0, None))
print("\n sigma      svd: err. abs   AtA: err. abs    lambda(AtA)")
for i in range(n):
    print(f"{s[i]:8.1e}     {abs(s_svd[i] - s[i]):9.1e}       {abs(s_ata[i] - s[i]):9.1e}      {lam[i]: .1e}")

The table repeats the interactive with different numbers: SVD has absolute error at most 2.2×10−162.2\times 10^{-16} for all singular values, and λi(A⊤A)\sqrt{\lambda_i(\mat{A}\T\mat{A})} has error of order u/σiu/\sigma_i while σi≳10−8\sigma_i \gtrsim 10^{-8} (for example 10−1410^{-14} with σ=2.8×10−3\sigma = 2.8\times 10^{-3} and 2.7×10−122.7\times 10^{-12} with σ=8.1×10−6\sigma = 8.1\times 10^{-6}). Below that it returns numbers of order 10−910^{-9} unrelated to truth, and the last two eigenvalues are negative: clipped to 0, the error is σi\sigma_i itself. Singular values of 10−1410^{-14} from SVD have relative error 5×10−45\times 10^{-4}, no better: that is the problem’s limit, since storing A\mat{A} in float64 already perturbs it by u∥A∥u\norm{\mat{A}}.

Sensitivity: Bauer–Fike, non-normal matrices and pseudospectra

For symmetric matrices Weyl says it all. For others, “how much does an eigenvalue move if the matrix moves?” has very different answers depending on the matrix; knowing them distinguishes algorithm failure from an ill-conditioned problem.

Proof

If μ\mu is an eigenvalue of A\mat{A} there is nothing to prove. Otherwise Λ−μI\mat{\Lambda} - \mu\mat{I} is invertible. Since A+E−μI\mat{A} + \mat{E} - \mu\mat{I} is singular, so are V−1(A+E−μI)V=(Λ−μI)+V−1EV\mat{V}\inv(\mat{A} + \mat{E} - \mu\mat{I})\mat{V} = (\mat{\Lambda} - \mu\mat{I}) + \mat{V}\inv\mat{E}\mat{V} and therefore I+(Λ−μI)−1V−1EV\mat{I} + (\mat{\Lambda} - \mu\mat{I})\inv\mat{V}\inv\mat{E}\mat{V}. A matrix I+K\mat{I} + \mat{K} with ∥K∥2<1\norm{\mat{K}}_2 < 1 is invertible (its Neumann series converges), so 1≤∥(Λ−μI)−1V−1EV∥2≤1min⁡i∣λi−μ∣ κ2(V)∥E∥21 \le \norm{(\mat{\Lambda} - \mu\mat{I})\inv\mat{V}\inv\mat{E}\mat{V}}_2 \le \frac{1}{\min_i\abs{\lambda_i - \mu}}\,\kappa_2(\mat{V})\norm{\mat{E}}_2, because the 2-norm of diagonal (Λ−μI)−1(\mat{\Lambda} - \mu\mat{I})\inv is 1/min⁡i∣λi−μ∣1/\min_i\abs{\lambda_i - \mu}.

∎

This is eigenvalue sensitivity in its simplest form. If A\mat{A} is normal (AA∗=A∗A\mat{A}\mat{A}^* = \mat{A}^*\mat{A}: symmetric, skew-symmetric, orthogonal, circulant…), it is diagonalizable by a unitary matrix, κ2(V)=1\kappa_2(\mat{V}) = 1, and no eigenvalue moves more than ∥E∥2\norm{\mat{E}}_2. Otherwise factor κ2(V)\kappa_2(\mat{V}) can be huge, and if A\mat{A} is defective there is no V\mat{V} and the bound says nothing.

The Bauer–Fike bound treats all eigenvalues alike. For a simple λ\lambda there is an individual measure: if x\vb{x} and y\vb{y} are its right and left eigenvectors (Ax=λx\mat{A}\vb{x} = \lambda\vb{x}, y∗A=λy∗\vb{y}^*\mat{A} = \lambda\vb{y}^*), a first-order expansion gives

λ(A+εE)=λ+ε y∗Exy∗x+O(ε2),κ(λ)=∥x∥2∥y∥2∣y∗x∣=1cos⁡∠(x,y).\lambda(\mat{A} + \eps\mat{E}) = \lambda + \eps\,\frac{\vb{y}^*\mat{E}\vb{x}}{\vb{y}^*\vb{x}} + \bigO(\eps^2), \qquad \kappa(\lambda) = \frac{\norm{\vb{x}}_2\norm{\vb{y}}_2}{\abs{\vb{y}^*\vb{x}}} = \frac{1}{\cos\angle(\vb{x}, \vb{y})}.

For normal matrices x\vb{x} and y\vb{y} coincide and κ(λ)=1\kappa(\lambda) = 1. The closer left and right eigenvectors are to perpendicular, the more sensitive the eigenvalue. scipy.linalg.eig(A, left=True) returns both, letting you compute κ(λ)\kappa(\lambda) for each.

The limiting case is Jordan block Jn\mat{J}_n (zeros on the diagonal, ones on the superdiagonal), whose only eigenvalue is 00. Perturbing only the bottom-left corner, Jn+ε ene1⊤\mat{J}_n + \eps\,\vb{e}_n\vb{e}_1\T has characteristic polynomial zn−εz^n - \eps: its eigenvalues are the nn nn-th roots of ε\eps, with magnitude ε1/n\eps^{1/n}. With n=8n = 8 and ε=10−16\eps = 10^{-16}, float64 rounding, eigenvalues move 10−210^{-2}.

Pseudospectra

Eigenvalues of a non-normal matrix are so fragile that asking for them in floating point is often the wrong question. The robust question is where eigenvalues of nearby matrices can lie.

Proof

(b) ⇔\Leftrightarrow (c): if z∉σ(A)z \notin \sigma(\mat{A}), ∥(zI−A)−1∥2=1/σmin⁡(zI−A)\norm{(z\mat{I} - \mat{A})\inv}_2 = 1/\sigma_{\min}(z\mat{I} - \mat{A}); if z∈σ(A)z \in \sigma(\mat{A}), σmin⁡=0\sigma_{\min} = 0. (a) ⇒\Rightarrow (b): if (A+E)v=zv(\mat{A} + \mat{E})\vb{v} = z\vb{v} with ∥v∥2=1\norm{\vb{v}}_2 = 1, then (zI−A)v=Ev(z\mat{I} - \mat{A})\vb{v} = \mat{E}\vb{v} and σmin⁡(zI−A)≤∥Ev∥2<ε\sigma_{\min}(z\mat{I} - \mat{A}) \le \norm{\mat{E}\vb{v}}_2 < \eps. (b) ⇒\Rightarrow (a): let s=σmin⁡(zI−A)<εs = \sigma_{\min}(z\mat{I} - \mat{A}) < \eps have unit singular vectors u,v\vb{u}, \vb{v}, meaning (zI−A)v=su(z\mat{I} - \mat{A})\vb{v} = s\vb{u}. With E=s uv∗\mat{E} = s\,\vb{u}\vb{v}^*, whose norm is s<εs < \eps, (A+E)v=Av+su=zv(\mat{A} + \mat{E})\vb{v} = \mat{A}\vb{v} + s\vb{u} = z\vb{v}.

∎

Form (b) is computed: evaluate σmin⁡(zI−A)\sigma_{\min}(z\mat{I} - \mat{A}) on a complex-plane grid and draw contours. For a normal matrix, σmin⁡(zI−A)=min⁡i∣z−λi∣\sigma_{\min}(z\mat{I} - \mat{A}) = \min_i\abs{z - \lambda_i} and σε\sigma_\eps is the union of disks of radius ε\eps centered on eigenvalues. For a non-normal matrix it can be much larger.

InteractivePseudospectra: when eigenvalues mislead
  • eigenvalues of A\mat{A}
  • eigenvalues of A+E\mat{A} + \mat{E}
  • boundary of σε\sigma_\varepsilon, ε=10−6\varepsilon = 10^{-6}
  • ε=10−1,…,10−12\varepsilon = 10^{-1}, \dots, 10^{-12}
Matrix
Size nn
−6.00
Computing…
Four triangular n×nn\times n matrices: normal (diag⁡(d)\diag(\vb{d}) with did_i equally spaced in [−0.8,0.8][-0.8, 0.8]), triangular with the same diagonal and ones on the superdiagonal, Jordan block Jn\mat{J}_n, and triangular Toeplitz with ones on the first two superdiagonals. Curves mark boundaries σmin⁡(zI−A)=ε\sigma_{\min}(z\mat{I} - \mat{A}) = \eps for ε=10−1,…,10−12\eps = 10^{-1}, \dots, 10^{-12}; orange is the chosen ε\eps. Blue points are float64 eigenvalues of A+E\mat{A} + \mat{E} for 160 random complex perturbations with ∥E∥F=ε\norm{\mat{E}}_F = \eps (hence ∥E∥2≤ε\norm{\mat{E}}_2 \le \eps): they always lie inside the orange curve. Compare eigenvalue movement for normal and Jordan matrices with the same ε\eps, and increase nn.

For the normal matrix, the cloud of perturbed eigenvalues is invisible for any small ε\eps: each moves at most ε\eps. For the size-8 Jordan block and ε=10−6\eps = 10^{-6}, the cloud is a ring of radius 0.130.13 to 0.150.15, of order ε1/8≈0.18\eps^{1/8} \approx 0.18 and five orders larger than the perturbation; contours are nearly concentric circles with radii growing like ε1/n\eps^{1/n}. The triangular matrix with distinct eigenvalues is diagonalizable, with κ2(V)=1.7×103\kappa_2(\mat{V}) = 1.7\times 10^3 for n=8n = 8 and 2.1×1052.1\times 10^5 for n=12n = 12: its disks merge into one elongated region as ε\eps grows. The Toeplitz matrix is also one Jordan block (nilpotent of rank n−1n - 1), but pseudospectra are not circles: with n=12n = 12 and ε=10−2\eps = 10^{-2} the boundary already has the loop shape of dashed curve eiθ+e2iθe^{i\theta} + e^{2i\theta}, obtained from its coefficients. Reichel and Trefethen (1992) proved that banded Toeplitz pseudospectra approach, as n→∞n \to \infty, those of the infinite Toeplitz operator, containing the region enclosed by that curve, the “symbol”, even though each finite matrix’s spectrum is only {0}\{0\}.

What does this mean for a computed eigenvalue? eig is backward stable: it returns exact eigenvalues of A+E\mat{A} + \mat{E} with ∥E∥2\norm{\mat{E}}_2 of order u∥A∥2u\norm{\mat{A}}_2. Computed eigenvalues lie in σcu∥A∥(A)\sigma_{cu\norm{\mat{A}}}(\mat{A}), and that is all one can guarantee: if that pseudospectrum is small, they are accurate; if large, no float64 algorithm will do better, because the problem itself does not determine eigenvalues more accurately.

[ ]Bauer–Fike, Jordan and individual eigenvalue sensitivityBrowser
import numpy as np
import scipy.linalg as sla

rng = np.random.default_rng(3)
n = 8

# 1. Bauer-Fike en una triangular no normal con autovalores distintos
d = np.linspace(-0.8, 0.8, n)
A = np.diag(d) + np.diag(np.ones(n - 1), 1)
w, VL, VR = sla.eig(A, left=True, right=True)
kV = np.linalg.cond(VR)
peor = 0.0
for _ in range(200):
    E = rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n))
    E *= 1e-10 / np.linalg.norm(E, 2)
    mu = np.linalg.eigvals(A + E)
    peor = max(peor, max(np.min(np.abs(d - m)) for m in mu))
print(f"triangular: kappa_2(V) = {kV:.1e}; con ||E||_2 = 1e-10, mayor desplazamiento = {peor:.1e}, cota = {kV * 1e-10:.1e}")
kappa = 1 / np.abs(np.sum(VL.conj() * VR, axis=0))     # columnas unitarias: 1 / |y^* x|
orden = np.argsort(w.real)
print("kappa(lambda_i):", np.array2string(kappa[orden], formatter={"float_kind": lambda t: f"{t:.1e}"}))

# 2. Jordan: la esquina eps da las raíces n-ésimas de eps
J = np.diag(np.ones(n - 1), 1)
for eps in (1e-16, 1e-8, 1e-4):
    Je = J.copy(); Je[-1, 0] = eps
    print(f"J_8 + eps e_8 e_1^T, eps = {eps:.0e}: max |lambda| = {np.abs(np.linalg.eigvals(Je)).max():.3f},  eps^(1/8) = {eps ** (1 / 8):.3f}")

# 3. el redondeo basta: J_8 girada por una ortogonal aleatoria
Q, _ = np.linalg.qr(rng.normal(size=(n, n)))
lam = np.linalg.eigvals(Q @ J @ Q.T)
print(f"eigvals(Q J_8 Q^T): max |lambda| = {np.abs(lam).max():.3f}   (exacto: 0; u^(1/8) = {(2.0**-53) ** (1 / 8):.3f})")

# 4. no normalidad en el tiempo: radio espectral 0.9 y, aun así, ||A^k|| crece
B = 0.9 * np.eye(n) + 0.9 * J
normas = [np.linalg.norm(np.linalg.matrix_power(B, k), 2) for k in range(0, 121)]
kmax = int(np.argmax(normas))
print(f"\nB = 0.9 (I + J_8): radio espectral 0.9, max_k ||B^k|| = {max(normas):.0f} en k = {kmax}, ||B^120|| = {normas[120]:.1f}")

The size-8 triangular matrix has κ2(V)=1.7×103\kappa_2(\mat{V}) = 1.7\times 10^{3} and comfortably satisfies Bauer–Fike: with ∥E∥2=10−10\norm{\mat{E}}_2 = 10^{-10} the largest movement in 200 perturbations is 2.1×10−82.1\times 10^{-8}, about 8 times below the bound because a random perturbation does not choose the most damaging direction. Even so, it is 200 times the perturbation. Individual condition numbers κ(λi)\kappa(\lambda_i) range from 29 at the extremes to 410 in the center: eigenvalues are not equally sensitive, and Bauer–Fike, seeing only κ2(V)\kappa_2(\mat{V}), is pessimistic for all. The Jordan block reproduces the nn-th roots: ε=10−16\eps = 10^{-16} moves the eigenvalue 0.0100.010, and ε=10−8\eps = 10^{-8} moves it 0.1000.100. Merely writing J8\mat{J}_8 in another orthonormal basis, without deliberate perturbation, makes eigvals return eigenvalues 0.0080.008 away from 0: rounding the similarity itself is the perturbation. Finally B=0.9(I+J8)\mat{B} = 0.9(\mat{I} + \mat{J}_8) has spectral radius 0.90.9, so Bk→0\mat{B}^k \to \mat{0}, but ∥Bk∥2\norm{\mat{B}^k}_2 rises to 7.6×1057.6\times 10^{5} at k=69k = 69 and at k=120k = 120 it is still 1.9×1051.9\times 10^{5}. Eigenvalues describe the limit; pseudospectra describe transient behavior. Trefethen and Embree (chapter 16) quantify this: for every ε>0\eps > 0, sup⁡k∥Ak∥2≥(ρε(A)−1)/ε\sup_k\norm{\mat{A}^k}_2 \ge (\rho_\eps(\mat{A}) - 1)/\eps, where ρε\rho_\eps is the greatest magnitude of a point in σε(A)\sigma_\eps(\mat{A}).

PageRank: power iteration at scale

Return to the first example. In a directed graph with NN nodes, let wij≥0w_{ij} \ge 0 be the weight of the link from jj to ii and P\mat{P} the column-stochastic matrix with pij=wij/∑kwkjp_{ij} = w_{ij}/\sum_k w_{kj}: from jj, jump to ii with probability proportional to weight. Google’s matrix mixes P\mat{P} with uniform jumps:

G=αP+1−αN11⊤,α=0.85 tıˊpicamente,\mat{G} = \alpha\mat{P} + \frac{1 - \alpha}{N}\vb{1}\vb{1}\T, \qquad \alpha = 0.85 \text{ típicamente},

and the PageRank vector is stationary distribution Gπ=π\mat{G}\vb{\pi} = \vb{\pi}, 1⊤π=1\vb{1}\T\vb{\pi} = 1 (Brin and Page, 1998). G\mat{G} is dense and never formed: since 1⊤x=1\vb{1}\T\vb{x} = 1 for any distribution,

Gx=α Px+1−αN1,\mat{G}\vb{x} = \alpha\,\mat{P}\vb{x} + \frac{1 - \alpha}{N}\vb{1},

a sparse product costing proportionally to the number of links. Nodes without outgoing links (dangling nodes) leave zero columns in P\mat{P}; conventionally their mass is distributed uniformly, adding another rank-one term that is not formed. Convergence speed is ∣λ2(G)∣≤α\abs{\lambda_2(\mat{G})} \le \alpha (Haveliwala and Kamvar, 2003), independent of graph size. Moreover, for two distributions x,x′\vb{x}, \vb{x}', Gx−Gx′=αP(x−x′)\mat{G}\vb{x} - \mat{G}\vb{x}' = \alpha\mat{P}(\vb{x} - \vb{x}'), and column-stochastic P\mat{P} does not increase the 1-norm, so ∥xk−π∥1≤2αk\norm{\vb{x}_k - \vb{\pi}}_1 \le 2\alpha^k. With α=0.85\alpha = 0.85, every iteration gains at least 0.070.07 digits, and 175 iterations guarantee error ≤10−12\le 10^{-12} for any graph.

[ ]PageRank of Les Misérables with a CSR matrixBrowser
import numpy as np
import scipy.sparse as sp
import networkx as nx

G = nx.les_miserables_graph()                  # coapariciones de personajes (Knuth, 1993): 77 nodos, 254 aristas con peso
nodos = list(G.nodes())
W = nx.to_scipy_sparse_array(G, nodelist=nodos, weight="weight", format="csr")
grado = np.asarray(W.sum(axis=0)).ravel()      # peso total de las aristas de cada nodo
P = sp.csr_array(W @ sp.diags_array(1.0 / grado))   # estocástica por columnas, dispersa
print(f"N = {P.shape[0]}, no nulos = {P.nnz} de {P.shape[0] ** 2} ({P.nnz / P.shape[0] ** 2:.1%})")

def pagerank(P, alfa=0.85, tol=1e-12, max_iter=1000):
    N = P.shape[0]
    colgante = np.asarray(P.sum(axis=0)).ravel() == 0
    x = np.full(N, 1.0 / N)
    for k in range(1, max_iter + 1):
        x_nuevo = alfa * (P @ x) + (alfa * x[colgante].sum() + 1 - alfa) / N
        cambio = np.abs(x_nuevo - x).sum()
        x = x_nuevo
        if cambio < tol:
            return x, k
    return x, max_iter

pi, iters = pagerank(P)
ref = nx.pagerank(G, alpha=0.85, tol=1e-14)
print(f"iteraciones: {iters}   max |pi - networkx| = {np.max(np.abs(pi - np.array([ref[u] for u in nodos]))):.1e}")
print("top 5 PageRank:", [(nodos[i], round(pi[i], 4)) for i in np.argsort(-pi)[:5]])
print("top 5 por grado:", [(nodos[i], int(grado[i])) for i in np.argsort(-grado)[:5]])
lam = np.sort(np.abs(np.linalg.eigvals(P.toarray())))[::-1]
print(f"|lambda_2(P)| = {lam[1]:.4f}   alfa |lambda_2(P)| = {0.85 * lam[1]:.4f}")
for alfa in (0.5, 0.85, 0.95, 0.99):
    print(f"alfa = {alfa}: {pagerank(P, alfa)[1]} iteraciones")

The matrix has 8.6 % nonzero entries (on the real web, a tiny fraction), and 95 iterations give the same vector as networkx.pagerank to 10−1310^{-13}. Valjean leads both rankings but the rest differ. In a connected undirected graph, the stationary distribution without jumps (α=1\alpha = 1) is proportional to weighted degree; jumps with probability 1−α1 - \alpha separate PageRank from degree. Bishop Myriel is the striking case: 16th by total weight and 3rd by PageRank. Seven characters (Napoleon, Geborand, Cravatte…) appear only with him, and of the mass uniform jumps place on them, fraction α\alpha passes to Myriel next step. Since P\mat{P} comes from an undirected graph, it is similar to symmetric D−1/2WD−1/2\mat{D}^{-1/2}\mat{W}\mat{D}^{-1/2} and has real eigenvalues; ∣λ2(G)∣=α∣λ2(P)∣=0.79\abs{\lambda_2(\mat{G})} = \alpha\abs{\lambda_2(\mat{P})} = 0.79 bounds convergence rate. Bringing α\alpha toward 1 increases iterations (31, 95, 182 and 276): the model resembles the graph more and converges more slowly. Power iteration fits for three reasons: it only needs matrix-vector products, its spectral gap is guaranteed by α\alpha, and ranking does not require greater precision. For sparse problems needing several eigenvalues, Krylov subspace methods (Lanczos, Arnoldi) generalize power iteration and converge much faster.

The professional version

FunctionLAPACKReturnsWhen to use
np.linalg.eigvals, np.linalg.eiggeevunordered (complex) eigenvalues and eigenvectorsgeneral square matrix
scipy.linalg.eig(A, left=True)geevleft eigenvectors toocondition κ(λ)\kappa(\lambda), Markov chains
scipy.linalg.schurgees(real) Schur form and Schur vectorsnon-normal: stable orthonormal basis
np.linalg.eigh, eigvalshsyevdascending real eigenvalues, orthonormal vectorssymmetric or Hermitian, always
scipy.linalg.eigh(A, subset_by_index=...)syevra subsetthe kk largest or smallest of a dense matrix
scipy.linalg.eigh_tridiagonalstemr, stebztridiagonal eigenvaluestridiagonal already available (Lanczos)
np.linalg.svd, scipy.linalg.svdgesddU\mat{U}, descending σ\vb{\sigma}, V⊤\mat{V}\Tdense SVD; full_matrices=False almost always
scipy.sparse.linalg.eigsh, eigs, svdsARPACKextreme kk of a sparse matrix or operatorlarge and sparse (next lesson)
torch.linalg.eigh, torch.linalg.svdcuSOLVER / LAPACKsame, on GPU and differentiableinside a model
[ ]Final comparison: ours versus LAPACKBrowser
import numpy as np
import scipy.linalg as sla

rng = np.random.default_rng(7)
n = 60
S = rng.normal(size=(n, n)); S = (S + S.T) / 2
G = rng.normal(size=(n, n))

lam_s, _ = qr_autovalores(S)
lam_g, _ = qr_autovalores(G)
print("simétrica, max |nuestro - eigvalsh|:", f"{np.max(np.abs(np.sort(lam_s.real) - sla.eigvalsh(S))):.1e}")
ref = sla.eigvals(G)
print("general,   max dist. a eigvals:     ", f"{max(np.min(np.abs(ref - l)) for l in lam_g):.1e}")
print("pares complejos en G:", int(np.sum(ref.imag > 0)))

# potencia, inversa y Rayleigh contra eigh, en la misma simétrica
w, V = sla.eigh(S)
rho, x, k = potencia(S, np.ones(n), tol=1e-10)
j = np.argmax(np.abs(w))
print(f"\npotencia: {k} iteraciones hacia lambda = {w[j]:.6f} (|l2/l1| = {np.sort(np.abs(w))[-2] / np.abs(w[j]):.3f}),"
      f" |rho - lambda| = {abs(rho - w[j]):.1e}")

# signo libre: comparar autovectores por el ángulo, no por las componentes
v_ref = V[:, j]
print("componentes iguales:", np.allclose(x, v_ref), "  ángulo:", f"{np.linalg.norm(x - (x @ v_ref) * v_ref):.1e}")

# SVD: gesdd frente a gesvd, mismos valores
A = rng.normal(size=(80, 30))
s1 = sla.svd(A, compute_uv=False, lapack_driver="gesdd")
s2 = sla.svd(A, compute_uv=False, lapack_driver="gesvd")
print(f"\nsvd gesdd frente a gesvd: max diferencia {np.max(np.abs(s1 - s2)):.1e}")

The final comparison confirms expectations: our QR matches LAPACK to 10−1310^{-13} even on a general matrix with 26 complex pairs; power iteration needs 1908 iterations on random symmetric 60×6060\times 60 because ∣λ2/λ1∣=0.988\abs{\lambda_2/\lambda_1} = 0.988 (random matrices have tightly clustered extreme eigenvalues); and an eigenvector computed two ways has opposite signs, so components differ even though their angle is 2×10−102\times 10^{-10}.

Common mistakes

Connections and further reading

  • Theory (eigenvalues, the spectral theorem, SVD, Jordan form) is in linear algebra; here we compute it. Revisit Jordan form if the behavior of ε1/n\eps^{1/n} surprises you.
  • Spectral graph methods (spectral clustering, embeddings, personalized PageRank) compute Laplacian eigenvectors with these algorithms or Krylov variants: normalized Laplacians.
  • PCA, spectral embeddings and truncated SVD use eigh, svd or randomized SVD, which uses QR and a small dense SVD.
  • A network’s Hessian spectrum is estimated by power iteration (or Lanczos) on Hessian-vector products, as in the first section.
  • Further reading: Trefethen and Bau, lectures 24–31, tell this story in greater detail; Golub and Van Loan, chapters 7 and 8, cover algorithms and costs; Parlett covers the symmetric case; Trefethen and Embree cover pseudospectra.

Exercises

NumericHow many Hessian-vector products?
You estimate a network Hessian's largest eigenvalue by power iteration using Hessian-vector products. If ∣λ2/λ1∣=0.9\abs{\lambda_2/\lambda_1} = 0.9, what is the smallest iteration count kk reducing eigenvector error by a factor 10610^6 according to bound ∣λ2/λ1∣k\abs{\lambda_2/\lambda_1}^k?
NumericThe eigenvalue converges twice as fast
The same symmetric Hessian has ∣λ2/λ1∣=0.9\abs{\lambda_2/\lambda_1} = 0.9. If you need the eigenvalue estimated by Rayleigh quotient ρk\rho_k, what is the smallest kk reducing the ρk\rho_k error bound by a factor 10610^6?
NumericWell-aimed inverse iteration
A\mat{A} is symmetric with eigenvalues 11, 33 and 77. You use inverse iteration with fixed shift σ=2.9\sigma = 2.9. What is the smallest iteration count reducing eigenvector error by a factor 101210^{12} according to the asymptotic convergence factor?
NumericWilkinson's shift
The final 2×22\times 2 block of a symmetric tridiagonal matrix is [2111]\begin{bmatrix} 2 & 1 \\ 1 & 1 \end{bmatrix}. What Wilkinson shift μ\mu is used in the next QR step? Give four digits.
NumericWhere AᵀA loses the SVD
You compute float64 singular values of A\mat{A} as λi(A⊤A)\sqrt{\lambda_i(\mat{A}\T\mat{A})}, with σ1=1\sigma_1 = 1. Ignoring dimension-dependent constants, below what σi\sigma_i are no correct digits left? Use unit roundoff u=2−53u = 2^{-53}.
Quizeig or eigh for covariance
You have a covariance matrix C∈R500×500\mat{C} \in \R^{500\times 500} calculated from 300 samples. Which statements are true?

More than one answer may be correct.

QuizAlgorithm failure?
You compute eigenvalues of a non-normal size-50 matrix A\mat{A} with ∥A∥2=1\norm{\mat{A}}_2 = 1 using np.linalg.eigvals. Perturbing one entry by 10−1010^{-10} moves an eigenvalue by 10−310^{-3}. What is correct?

More than one answer may be correct.

QuizThe shift that does not move
You apply QR with Rayleigh shift μk=(Ak)nn\mu_k = (\mat{A}_k)_{nn} to the symmetric zero-diagonal Golub–Kahan tridiagonal, whose eigenvalues are ±σ1,…,±σn\pm\sigma_1, \dots, \pm\sigma_n. What happens in exact arithmetic?
ProofPower iteration convergence
Prove: Let A\mat{A} be diagonalizable with eigenvalues ∣λ1∣>∣λ2∣≥⋯≥∣λn∣\abs{\lambda_1} > \abs{\lambda_2} \ge \cdots \ge \abs{\lambda_n} and unit eigenvectors vi\vb{v}_i, and let x0=∑icivi\vb{x}_0 = \sum_i c_i\vb{v}_i with c1≠0c_1 \neq 0. Then sin⁡∠(xk,v1)≤C∣λ2/λ1∣k\sin\angle(\vb{x}_k, \vb{v}_1) \le C\abs{\lambda_2/\lambda_1}^k for a constant CC independent of kk.
0
Normalized iterates xk\vb{x}_k point in the direction of Akx0\mat{A}^k\vb{x}_0, because normalization changes only length.

Step 1 of 4. How do you write Akx0\mat{A}^k\vb{x}_0?

CodeRobust Rayleigh quotient iteration
Implement rayleigh_quotient_iteration(A, x0, tol=1e-12, max_iter=20) for symmetric A\mat{A}. Return (lam, x, k): eigenvalue, unit eigenvector and number of iterations performed (systems solved). Robust stopping criterion: before each solve, check residual ∥Ax−ρx∥2≤tol⋅∥A∥1\norm{\mat{A}\vb{x} - \rho\vb{x}}_2 \le \text{tol}\cdot\norm{\mat{A}}_1 and stop if satisfied; if np.linalg.solve fails because A−ρI\mat{A} - \rho\mat{I} is exactly singular, or returns nonfinite values, the current vector is already an eigenvector: stop then too. Do not call eig or eigh.
import numpy as np

def rayleigh_quotient_iteration(A, x0, tol=1e-12, max_iter=20):
  """Devuelve (lam, x, k) con A x = lam x, ||x|| = 1 y k sistemas resueltos."""
  A = np.asarray(A, dtype=float)
  x = np.asarray(x0, dtype=float)
  x = x / np.linalg.norm(x)
  escala = np.linalg.norm(A, 1)
  k = 0
  # tu código: rho = cociente de Rayleigh, residuo, parada, solve protegido, normalizar
  lam = x @ A @ x
  return lam, x, k
Shift+Enter to run

Summary

Key idea
Programs do not compute eigenvalues through the characteristic polynomial: they iterate orthogonal similarities. First a finite reduction to Hessenberg or tridiagonal form, then QR steps with Wilkinson shifts and deflation, which act as Rayleigh quotient iterations in the last row and converge in two or three steps per eigenvalue.
  • Power iteration only needs Ax\mat{A}\vb{x} products and converges as ∣λ2/λ1∣k\abs{\lambda_2/\lambda_1}^k (the Rayleigh quotient at its square if A\mat{A} is symmetric). Stop using the residual, a backward error. It is useful for PageRank and network Hessians.
  • Inverse iteration with shift σ\sigma targets the eigenvalue nearest σ\sigma with factor ∣λJ−σ∣/∣λK−σ∣\abs{\lambda_J - \sigma}/\abs{\lambda_K - \sigma}; Rayleigh quotient shifts give cubic convergence for symmetric matrices, but do not let you choose the destination.
  • QR is simultaneous iteration; Hessenberg reduces each step to O(n2)\bigO(n^2), shifts make its last row Rayleigh iteration, Wilkinson ensures it starts, and Francis uses real arithmetic with an implicit double shift.
  • For symmetric matrices, eigh: eigenvalues with absolute error u∥A∥u\norm{\mat{A}} (Weyl), orthonormal vectors and lower cost. SVD uses Golub–Kahan bidiagonalization, never A⊤A\mat{A}\T\mat{A}, which loses σi<u σ1\sigma_i < \sqrt{u}\,\sigma_1.
  • A stable algorithm’s computed eigenvalue is exact for a nearby matrix; its error depends on sensitivity: κ2(V)\kappa_2(\mat{V}) in Bauer–Fike, 1/∣y∗x∣1/\abs{\vb{y}^*\vb{x}} for each eigenvalue, ε1/n\eps^{1/n} in a Jordan block. Pseudospectra map sensitivity and explain non-normal transient behavior.