Module contents
Lesson 12 of 25Core 95 min

Symmetric matrices, the spectral theorem and quadratic forms

Real symmetric matrices such as covariances, Hessians, Gram matrices and Laplacians have real eigenvalues and orthonormal eigenbases. Prove the spectral theorem, classify quadratic forms, characterize eigenvalues with Rayleigh and Courant–Fischer, and study how perturbations affect eigenvalues and eigenvectors.

After this lesson you can

  • Prove that a real symmetric matrix has real eigenvalues and that eigenvectors for distinct eigenvalues are orthogonal.
  • Prove the spectral theorem by induction and express A as a weighted sum of rank-one projectors.
  • Classify quadratic forms and sketch their level sets from the spectral decomposition.
  • Use the Rayleigh quotient and Courant–Fischer to bound and characterize eigenvalues.
  • Use Weyl’s inequality and the spectral gap to predict eigenvalue and eigenvector changes under perturbation.

Before you start

Motivation: the matrices you actually diagonalize

In the previous two lessons, the eigenvectors of an arbitrary matrix caused plenty of trouble. A rotation of the plane (except for 0°0° and 180°180°) has no real eigenvalues (they are complex). A shear does not have enough eigenvectors and cannot be diagonalized: it needs Jordan form. Even when a matrix is diagonalizable, its eigenbasis may be so close to degenerate that VΛV−1\mat{V}\mat{\Lambda}\mat{V}\inv amplifies any rounding error.

Now look at where the matrices you diagonalize in practice come from:

  • Covariances. Σ=E[(x−μ)(x−μ)⊤]\mat{\Sigma} = \E[(\vb{x} - \vb{\mu})(\vb{x} - \vb{\mu})\T] is an average of matrices vv⊤\vb{v}\vb{v}\T, each equal to its transpose. The covariance matrix is symmetric, and PCA diagonalizes it.
  • Hessians. If ff has continuous second derivatives, ∂i∂jf=∂j∂if\partial_i\partial_j f = \partial_j\partial_i f (Schwarz’s theorem), so the Hessian is symmetric. Its spectrum tells us whether a critical point of the loss is a minimum, maximum, or saddle, and how much the surface curves in each direction.
  • Gram matrices. X⊤X\mat{X}\T\mat{X} in the normal equations, or a kernel matrix Kij=k(xi,xj)K_{ij} = k(\vb{x}_i, \vb{x}_j): entries that are inner products, symmetric by definition.
  • Graph Laplacians. L=D−W\mat{L} = \mat{D} - \mat{W} with weights wij=wjiw_{ij} = w_{ji}. The Laplacian satisfies x⊤Lx=∑i<jwij(xi−xj)2\vb{x}\T\mat{L}\vb{x} = \sum_{i \lt j} w_{ij}(x_i - x_j)^2 and its eigenvectors form the basis of spectral clustering.

For these matrices everything is clean: eigenvalues are real, eigenvectors can be chosen orthonormal, and the matrix can be written A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T with Q\mat{Q} orthogonal. This is the spectral theorem, and it explains why PCA, second-order methods, Gaussian processes, and spectral graph methods work so well in practice.

In this lesson you will prove it, use it to understand the geometry of quadratic forms x⊤Ax\vb{x}\T\mat{A}\vb{x} (ellipses, saddles, channels), and see that eigenvalues of a symmetric matrix have a variational characterization, as maxima and minima of a quotient, that bounds them without computing them. This leads to the most useful practical result: eigenvalues of a symmetric matrix are extraordinarily stable under noise, whereas eigenvectors may not be stable at all. You will finish by implementing Jacobi’s method, the first algorithm for this problem, and comparing it with numpy.linalg.eigh.

What symmetry changes

Every square matrix splits uniquely into symmetric and skew-symmetric parts:

M=12(M+M⊤)⏟S simeˊtrica+12(M−M⊤)⏟K antisimeˊtrica.\mat{M} = \underbrace{\tfrac{1}{2}(\mat{M} + \mat{M}\T)}_{\mat{S}\ \text{simétrica}} + \underbrace{\tfrac{1}{2}(\mat{M} - \mat{M}\T)}_{\mat{K}\ \text{antisimétrica}} .

In 2×22\times 2, K=[0k−k0]\mat{K} = \begin{bmatrix} 0 & k \\ -k & 0 \end{bmatrix} is kk times a rotation through −90°-90°. The symmetric part stretches and compresses along certain axes; the skew-symmetric part pushes each vector perpendicular to itself. The interactive lets you mix the two and see what happens to the eigenvectors.

InteractiveThe symmetric and skew-symmetric parts
The shaded ellipse is the image of the unit circle. With k=0k = 0 the two eigenlines are perpendicular and coincide with the axes of the ellipse: eigenvectors are the directions of maximum and minimum stretching. Increase kk slowly: the eigenlines tilt toward each other, move away from the ellipse axes, and κ(V)\kappa(\mat{V}) grows; when k2k^2 exceeds ((a−d)/2)2+s2((a - d)/2)^2 + s^2 they merge and the eigenvalues become complex. Drag x\vb{x} around the circle: Ax\mat{A}\vb{x} is parallel to x\vb{x} only on the eigenlines.

What you just saw, with k=0k = 0, is the whole lesson in miniature:

  1. The eigenvalues are real. The discriminant of [assd]\begin{bmatrix} a & s \\ s & d \end{bmatrix} is (a−d)2+4s2≥0(a - d)^2 + 4s^2 \ge 0, never negative. With the skew-symmetric part it becomes (a−d)2+4s2−4k2(a - d)^2 + 4s^2 - 4k^2, which can be negative.
  2. The eigenvectors are perpendicular and form an orthonormal basis: the change-of-basis matrix is a rotation (or reflection), with condition number 1.
  3. The axes of the image ellipse are the eigenvectors, and its semiaxes measure ∣λ1∣\abs{\lambda_1} and ∣λ2∣\abs{\lambda_2}.

All three generalize to any dimension. One identity is enough to prove them.

Real eigenvalues and orthogonal eigenvectors

Symmetry has a coordinate-free interpretation: A\mat{A} can be moved from one side of the inner product to the other.

Proof

(Ax)⊤y=x⊤A⊤y(\mat{A}\vb{x})\T\vb{y} = \vb{x}\T\mat{A}\T\vb{y} by the properties of the transpose, so if A⊤=A\mat{A}\T = \mat{A} the two expressions coincide. Conversely, with x=ei\vb{x} = \vb{e}_i and y=ej\vb{y} = \vb{e}_j the equality says aji=aija_{ji} = a_{ij}.

∎
Proof

The characteristic polynomial has nn roots in C\C. Let λ∈C\lambda \in \C be one of them and x∈Cn\vb{x} \in \C^n, x≠0\vb{x} \ne \vb{0}, with Ax=λx\mat{A}\vb{x} = \lambda\vb{x}. Write xˉ\bar{\vb{x}} for the entrywise conjugate and consider the number

s=xˉ⊤Ax.s = \bar{\vb{x}}\T\mat{A}\vb{x} .

On one hand, s=xˉ⊤(λx)=λ xˉ⊤x=λ∑i∣xi∣2s = \bar{\vb{x}}\T(\lambda\vb{x}) = \lambda\,\bar{\vb{x}}\T\vb{x} = \lambda\sum_i \abs{x_i}^2, and ∑i∣xi∣2>0\sum_i\abs{x_i}^2 > 0 is real. On the other, since A\mat{A} is real, sˉ=x⊤Axˉ\bar{s} = \vb{x}\T\mat{A}\bar{\vb{x}}; that number is an 1×11\times 1 matrix, equal to its transpose: sˉ=xˉ⊤A⊤x=xˉ⊤Ax=s\bar{s} = \bar{\vb{x}}\T\mat{A}\T\vb{x} = \bar{\vb{x}}\T\mat{A}\vb{x} = s. Hence ss is real, and so is λ=s/∑i∣xi∣2\lambda = s / \sum_i \abs{x_i}^2.

For the eigenvector: A−λI\mat{A} - \lambda\mat{I} is a singular real matrix, so its kernel contains nonzero real vectors (Gaussian elimination on a real matrix produces a real basis for the kernel).

∎

Symmetry was used in just one place: A⊤=A\mat{A}\T = \mat{A} to close the chain sˉ=s\bar{s} = s. With a rotation the chain breaks and the complex eigenvalues e±iθe^{\pm i\theta} from the eigenvalue lesson appear. Eigenvector orthogonality follows from the same idea, and you will prove it yourself.

ProofEigenvectors of distinct eigenvalues
Prove: If A=A⊤\mat{A} = \mat{A}\T, Ax=λx\mat{A}\vb{x} = \lambda\vb{x} and Ay=μy\mat{A}\vb{y} = \mu\vb{y} with λ≠μ\lambda \ne \mu, then x⊤y=0\vb{x}\T\vb{y} = 0.
0
Let x,y∈Rn\vb{x}, \vb{y} \in \R^n be nonzero and λ,μ\lambda, \mu be distinct real numbers, as stated.

Step 1 of 4. Which quantity is useful to compute in two different ways?

The spectral theorem

This is the spectral theorem. It says that “symmetric” and “diagonalizable in an orthonormal basis” mean exactly the same thing. The easy implication is the reverse: (QΛQ⊤)⊤=QΛ⊤Q⊤=QΛQ⊤(\mat{Q}\mat{\Lambda}\mat{Q}\T)\T = \mat{Q}\mat{\Lambda}\T\mat{Q}\T = \mat{Q}\mat{\Lambda}\mat{Q}\T. The interesting one is the forward direction, proved by induction by removing one eigenvector at a time.

Proof

Induction on nn. For n=1n = 1 there is nothing to prove. Assume the result holds in dimension n−1n - 1 and let A\mat{A} be symmetric n×nn\times n.

Step 1: an eigenvector. By the previous theorem, A\mat{A} has a real eigenvalue λ1\lambda_1 with a real eigenvector, which we normalize: Aq1=λ1q1\mat{A}\vb{q}_1 = \lambda_1\vb{q}_1, ∥q1∥=1\norm{\vb{q}_1} = 1.

Step 2: the complement is invariant. Let W=q1⊥W = \vb{q}_1^\perp be the orthogonal complement of q1\vb{q}_1. If w∈W\vb{w} \in W, then Aw∈W\mat{A}\vb{w} \in W:

q1⊤(Aw)=(Aq1)⊤w=λ1 q1⊤w=0.\vb{q}_1\T(\mat{A}\vb{w}) = (\mat{A}\vb{q}_1)\T\vb{w} = \lambda_1\,\vb{q}_1\T\vb{w} = 0 .

The first equality is the self-adjointness lemma: this is where symmetry is used.

Step 3: reduce the dimension. Extend q1\vb{q}_1 to an orthonormal basis of Rn\R^n (using Gram–Schmidt, for example) and call U∈Rn×(n−1)\mat{U} \in \R^{n\times(n-1)} the matrix of the n−1n - 1 new vectors, which are an orthonormal basis of WW. The matrix Q1=[ q1 U ]\mat{Q}_1 = [\,\vb{q}_1\ \mat{U}\,] is orthogonal and

Q1⊤AQ1=[q1⊤Aq1q1⊤AUU⊤Aq1U⊤AU]=[λ10⊤0B],B=U⊤AU.\mat{Q}_1\T\mat{A}\mat{Q}_1 = \begin{bmatrix} \vb{q}_1\T\mat{A}\vb{q}_1 & \vb{q}_1\T\mat{A}\mat{U} \\ \mat{U}\T\mat{A}\vb{q}_1 & \mat{U}\T\mat{A}\mat{U} \end{bmatrix} = \begin{bmatrix} \lambda_1 & \vb{0}\T \\ \vb{0} & \mat{B} \end{bmatrix}, \qquad \mat{B} = \mat{U}\T\mat{A}\mat{U} .

The lower-left block is U⊤(λ1q1)=0\mat{U}\T(\lambda_1\vb{q}_1) = \vb{0} because the columns of U\mat{U} are orthogonal to q1\vb{q}_1; the upper-right block is its transpose, because Q1⊤AQ1\mat{Q}_1\T\mat{A}\mat{Q}_1 is symmetric. And B∈R(n−1)×(n−1)\mat{B} \in \R^{(n-1)\times(n-1)} is symmetric: B⊤=U⊤A⊤U=B\mat{B}\T = \mat{U}\T\mat{A}\T\mat{U} = \mat{B}.

Step 4: induction. By hypothesis, B=Q~Λ~Q~⊤\mat{B} = \tilde{\mat{Q}}\tilde{\mat{\Lambda}}\tilde{\mat{Q}}\T with Q~\tilde{\mat{Q}} orthogonal. Then

Q=Q1[10⊤0Q~]\mat{Q} = \mat{Q}_1\begin{bmatrix} 1 & \vb{0}\T \\ \vb{0} & \tilde{\mat{Q}} \end{bmatrix}

is a product of orthogonal matrices, hence orthogonal, and Q⊤AQ=diag⁡(λ1,Λ~)\mat{Q}\T\mat{A}\mat{Q} = \diag(\lambda_1, \tilde{\mat{\Lambda}}). Multiplying by Q\mat{Q} on the left and Q⊤\mat{Q}\T on the right gives A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T.

∎

Three consequences to keep in mind:

  • Multiplicities. If λ\lambda appears mm times in Λ\mat{\Lambda}, its eigenspace has dimension mm: for a symmetric matrix the geometric multiplicity always matches the algebraic multiplicity. There are never Jordan blocks.
  • Uniqueness. Λ\mat{\Lambda} is unique up to order. Q\mat{Q} is not: each column can change sign, and if an eigenvalue is repeated mm times, any orthonormal basis of its eigenspace works. This freedom causes the eigenvector fragility you will see later.
  • Hermitian version. If A∈Cn×n\mat{A} \in \C^{n\times n} satisfies AH=A\mat{A}^{\mathsf{H}} = \mat{A} (conjugate transpose), the same proof with xˉ⊤\bar{\vb{x}}\T instead of x⊤\vb{x}\T gives A=UΛUH\mat{A} = \mat{U}\mat{\Lambda}\mat{U}^{\mathsf{H}} with U\mat{U} unitary and Λ\mat{\Lambda} real. This version is used in quantum mechanics, where observables are Hermitian operators.

The matrix as a sum of projectors

Write the product QΛQ⊤\mat{Q}\mat{\Lambda}\mat{Q}\T column by row:

A=∑i=1nλi qiqi⊤.\mat{A} = \sum_{i=1}^{n} \lambda_i\,\vb{q}_i\vb{q}_i\T .

Each qiqi⊤\vb{q}_i\vb{q}_i\T is the orthogonal projection matrix onto the line of qi\vb{q}_i. The action of A\mat{A} on a vector has three stages:

Ax=∑i=1nλi (qi⊤x) qi:\mat{A}\vb{x} = \sum_{i=1}^n \lambda_i\,(\vb{q}_i\T\vb{x})\,\vb{q}_i :

compute the coordinates of x\vb{x} in the eigenbasis (Q⊤x\mat{Q}\T\vb{x}), multiply each by its eigenvalue (Λ\mat{\Lambda}), and recombine (Q\mat{Q}). A symmetric matrix is a collection of nn independent stretches along nn perpendicular directions.

Grouping repeated eigenvalues gives A=∑kμkPk\mat{A} = \sum_k \mu_k\mat{P}_k, where μ1,…,μr\mu_1, \dots, \mu_r are the distinct eigenvalues and Pk\mat{P}_k is the orthogonal projector onto the eigenspace of μk\mu_k. This form is unique, even if Q\mat{Q} is not, and the projectors satisfy

Pk2=Pk=Pk⊤,PkPl=0 (k≠l),∑kPk=I.\mat{P}_k^2 = \mat{P}_k = \mat{P}_k\T, \qquad \mat{P}_k\mat{P}_l = \mat{0}\ (k \ne l), \qquad \sum_k \mat{P}_k = \mat{I} .

The last identity is called the resolution of the identity. That is why, when two computed eigenvalues nearly coincide, the meaningful comparison between two programs is the projector onto their common eigenspace, not individual vectors.

The decomposition turns any function of the matrix into a function of numbers. Since Ak=QΛkQ⊤\mat{A}^k = \mat{Q}\mat{\Lambda}^k\mat{Q}\T, for a polynomial, and by extension for any matrix function,

f(A)=∑if(λi) qiqi⊤:f(\mat{A}) = \sum_i f(\lambda_i)\,\vb{q}_i\vb{q}_i\T :

the inverse (f(λ)=1/λf(\lambda) = 1/\lambda, if no λi\lambda_i is zero), the exponential etAe^{t\mat{A}} of dynamical systems, or the square root of a matrix with nonnegative eigenvalues, which will appear in the next lesson. Keeping the terms with largest ∣λi∣\abs{\lambda_i} gives the best low-rank approximation, which for a symmetric matrix matches the one given by the SVD: its singular values are the ∣λi∣\abs{\lambda_i}.

[ ]The spectral decomposition and its projectorsBrowser
import numpy as np

A = np.array([[2.0, 1.0, 0.0],
              [1.0, 2.0, 1.0],
              [0.0, 1.0, 2.0]])
w, Q = np.linalg.eigh(A)          # autovalores en orden ascendente
print("autovalores:", w)          # 2 - √2, 2, 2 + √2
print("¿Q ortogonal?", np.allclose(Q.T @ Q, np.eye(3)))

S = sum(w[i] * np.outer(Q[:, i], Q[:, i]) for i in range(3))
print("‖A − Σ λᵢ qᵢqᵢᵀ‖ =", np.linalg.norm(A - S))

P = [np.outer(Q[:, i], Q[:, i]) for i in range(3)]
print("P₁² = P₁:", np.allclose(P[0] @ P[0], P[0]),
      "  P₁P₂ = 0:", np.allclose(P[0] @ P[1], 0),
      "  ΣPᵢ = I:", np.allclose(sum(P), np.eye(3)))

# una función de la matriz: la raíz cuadrada (todos los autovalores son positivos)
raiz = Q @ np.diag(np.sqrt(w)) @ Q.T
print("‖√A·√A − A‖ =", np.linalg.norm(raiz @ raiz - A))

Quadratic forms

Requiring A\mat{A} to be symmetric loses no generality. For any M\mat{M}, the skew-symmetric part contributes nothing: if K⊤=−K\mat{K}\T = -\mat{K}, the number x⊤Kx\vb{x}\T\mat{K}\vb{x} equals its transpose x⊤K⊤x=−x⊤Kx\vb{x}\T\mat{K}\T\vb{x} = -\vb{x}\T\mat{K}\vb{x}, so it is zero. Thus x⊤Mx=x⊤Sx\vb{x}\T\mat{M}\vb{x} = \vb{x}\T\mat{S}\vb{x} with S=(M+M⊤)/2\mat{S} = (\mat{M} + \mat{M}\T)/2, and with the symmetry requirement the matrix of a form is unique.

Principal axes

The spectral theorem eliminates the cross terms. With the change of variables y=Q⊤x\vb{y} = \mat{Q}\T\vb{x}, a rotation (or reflection) that distorts nothing,

q(x)=x⊤QΛQ⊤x=y⊤Λy=λ1y12+λ2y22+⋯+λnyn2.q(\vb{x}) = \vb{x}\T\mat{Q}\mat{\Lambda}\mat{Q}\T\vb{x} = \vb{y}\T\mat{\Lambda}\vb{y} = \lambda_1y_1^2 + \lambda_2y_2^2 + \dots + \lambda_ny_n^2 .

This is the principal axes theorem. In the eigenvector axes, a quadratic form is a sum of weighted squares, and its level curves in the plane can be read directly:

  • λ1,λ2>0\lambda_1, \lambda_2 > 0. λ1y12+λ2y22=1\lambda_1y_1^2 + \lambda_2y_2^2 = 1 is an ellipse with semiaxes 1/λ11/\sqrt{\lambda_1} along q1\vb{q}_1 and 1/λ21/\sqrt{\lambda_2} along q2\vb{q}_2. The large eigenvalue gives the short semiaxis: where the form grows rapidly, level 1 is reached sooner. The enclosed area is π/λ1λ2=π/det⁡A\pi/\sqrt{\lambda_1\lambda_2} = \pi/\sqrt{\det\mat{A}}.
  • λ1>0>λ2\lambda_1 > 0 > \lambda_2. Hyperbolas. The zero level is the pair of lines y2=±λ1/∣λ2∣ y1y_2 = \pm\sqrt{\lambda_1/\abs{\lambda_2}}\,y_1, separating the region where q>0q > 0 from the region where q<0q \lt 0.
  • λ1>0=λ2\lambda_1 > 0 = \lambda_2. λ1y12=1\lambda_1y_1^2 = 1 consists of two lines parallel to q2\vb{q}_2: the form does not see direction q2\vb{q}_2 at all.

In the previous example, 5x2+4xy+2y2=15x^2 + 4xy + 2y^2 = 1 is a tilted ellipse with semiaxis 1/6≈0.411/\sqrt{6} \approx 0.41 in direction (2,1)(2, 1) and semiaxis 11 in direction (−1,2)(-1, 2).

InteractiveLevel curves of a quadratic form
Curves q=±0.25,±1,±2.25,…q = \pm 0.25, \pm 1, \pm 2.25, \dots (positive in red, negative in blue; the q=±1q = \pm 1 curves are thicker). Arrows show the semiaxes qi/∣λi∣\vb{q}_i/\sqrt{\abs{\lambda_i}} of level ±1\pm 1. Decrease cc from the bowl: when ac=b2ac = b^2 an eigenvalue becomes zero, the ellipse opens into two parallel lines (the channel) and, as you keep decreasing it, into hyperbolas. Turn on rotation to the eigenvector axes: the change y=Q⊤x\vb{y} = \mat{Q}\T\vb{x} straightens the figure and the cross term disappears.

Classification and inertia

According to the signs taken by q(x)q(\vb{x}) for x≠0\vb{x} \ne \vb{0}, the form (and its matrix) is positive definite if always q>0q > 0, positive semidefinite if always q≥0q \ge 0, negative definite or negative semidefinite with the inequalities reversed, and indefinite if it takes values of both signs. By the principal axes, this depends only on eigenvalue signs: positive definite means all λi>0\lambda_i > 0, positive semidefinite means all λi≥0\lambda_i \ge 0, indefinite means eigenvalues of both signs. The triple (n+,n−,n0)(n_+, n_-, n_0) giving the number of positive, negative, and zero eigenvalues is called the inertia of A\mat{A}. Positive definite matrices have their own lesson, the next one.

What if instead of Q\mat{Q} you use an arbitrary change of variables, x=Sz\vb{x} = \mat{S}\vb{z} with S\mat{S} invertible? The form now has matrix S⊤AS\mat{S}\T\mat{A}\mat{S} (a congruence, not a similarity), and its eigenvalues change. What does not change is their sign:

Proof

Let B=S⊤AS\mat{B} = \mat{S}\T\mat{A}\mat{S}, and let pp and p′p' be the numbers of positive eigenvalues of A\mat{A} and B\mat{B}. Suppose p>p′p > p'. Let V+V_+ be the span of the eigenvectors of A\mat{A} with positive eigenvalue: dim⁡V+=p\dim V_+ = p and x⊤Ax>0\vb{x}\T\mat{A}\vb{x} > 0 for every nonzero x∈V+\vb{x} \in V_+. Let ZZ be the span of the eigenvectors of B\mat{B} with eigenvalue ≤0\le 0: dim⁡Z=n−p′\dim Z = n - p' and z⊤Bz≤0\vb{z}\T\mat{B}\vb{z} \le 0 on ZZ. The space SZ\mat{S}Z has the same dimension, n−p′n - p', and for x=Sz∈SZ\vb{x} = \mat{S}\vb{z} \in \mat{S}Z, x⊤Ax=z⊤Bz≤0\vb{x}\T\mat{A}\vb{x} = \vb{z}\T\mat{B}\vb{z} \le 0. Since dim⁡V++dim⁡SZ=p+n−p′>n\dim V_+ + \dim \mat{S}Z = p + n - p' > n, the two subspaces share a nonzero vector, on which qq would be both >0> 0 and ≤0\le 0. Contradiction. By symmetry (A=S−TBS−1\mat{A} = \mat{S}^{-\mathsf{T}}\mat{B}\mat{S}\inv), neither can p′>pp' > p hold. The same argument with −A-\mat{A} equates the negative counts, and the zero count is what remains.

∎

The practical consequence is remarkable. If Gaussian elimination without row exchanges works on a symmetric matrix, it gives A=LDL⊤\mat{A} = \mat{L}\mat{D}\mat{L}\T with L\mat{L} unit lower triangular and D\mat{D} diagonal with the pivots (the LU factorization exploiting symmetry). This is a congruence, so the signs of the pivots match the signs of the eigenvalues. For example, [1221]\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} has pivots 11 and 1−4=−31 - 4 = -3: one positive eigenvalue and one negative (they are 33 and −1-1). Applied to A−σI\mat{A} - \sigma\mat{I}, the number of negative pivots counts how many eigenvalues of A\mat{A} are less than σ\sigma, without computing any. This count and bisection in σ\sigma locate any eigenvalue: this is what bisection algorithms for symmetric tridiagonal matrices do.

Bowls, saddles, and channels

The most important application is in optimization. Near a critical point x⋆\vb{x}^\star (zero gradient), the second-order Taylor expansion is

f(x⋆+h)≈f(x⋆)+12 h⊤Hh,H=∇2f(x⋆),f(\vb{x}^\star + \vb{h}) \approx f(\vb{x}^\star) + \tfrac{1}{2}\,\vb{h}\T\mat{H}\vb{h}, \qquad \mat{H} = \hess f(\vb{x}^\star),

and the local shape of ff is that of the Hessian’s quadratic form. If H\mat{H} is positive definite, the point is a strict local minimum (a bowl); if negative definite, a maximum; if indefinite, a saddle: there are directions in which ff decreases. If only semidefinite, the second-order term is insufficient and higher-order terms decide (the second-order conditions of optimization). Eigenvalues also tell us how much ff curves in each eigenvector direction: the section of the surface along the line of qi\vb{q}_i is the parabola 12λit2\tfrac{1}{2}\lambda_i t^2. This is the information studied in a network’s Hessian spectrum.

InteractiveBowls, saddles, and channels
The surface z=x⊤Axz = \vb{x}\T\mat{A}\vb{x} over a disk of radius 1.4, red where positive and blue where negative. The orange and aquamarine parabolas are sections along the eigenvector directions, z=λ1t2z = \lambda_1 t^2 and z=λ2t2z = \lambda_2 t^2. Set λ2\lambda_2 to zero (channel: a whole line of minima) and then negative (saddle). Turn on the surface in eigenvector axes to see that θ\theta only rotates the figure. In the plane panel, apply the factors one by one: Q⊤\mat{Q}\T rotates the eigenvectors onto the axes, Λ\mat{\Lambda} stretches each axis by its eigenvalue, and Q\mat{Q} undoes the rotation.

The Rayleigh quotient

From here on we order eigenvalues from largest to smallest, λ1≥λ2≥⋯≥λn\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_n (note: numpy.linalg.eigh returns them in ascending order).

R(cx)=R(x)R(c\vb{x}) = R(\vb{x}) for every c≠0c \ne 0: only the direction of x\vb{x} matters, so it suffices to study it on the unit sphere, where R(x)=x⊤AxR(\vb{x}) = \vb{x}\T\mat{A}\vb{x}. If x\vb{x} is an eigenvector, R(x)R(\vb{x}) is its eigenvalue. For other vectors, in eigenvector coordinates y=Q⊤x\vb{y} = \mat{Q}\T\vb{x},

R(x)=∑iλiyi2∑iyi2=∑iwi λi,wi=yi2∥y∥2≥0,∑iwi=1.R(\vb{x}) = \frac{\sum_i \lambda_i y_i^2}{\sum_i y_i^2} = \sum_i w_i\,\lambda_i, \qquad w_i = \frac{y_i^2}{\norm{\vb{y}}^2} \ge 0,\quad \sum_i w_i = 1 .

The Rayleigh quotient is a weighted average of the eigenvalues, with weights equal to the squares of the coordinates of x\vb{x} in the eigenbasis. An average cannot exceed the largest value averaged or fall below the smallest:

InteractiveRayleigh on the circle
Move x\vb{x} around the circle. The magenta arrow is Ax\mat{A}\vb{x}, the gray arrow its shadow on x\vb{x}, measuring exactly R(x)R(\vb{x}), and the purple arrow the remainder, Ax−R(x)x\mat{A}\vb{x} - R(\vb{x})\vb{x}. The polar curve plots R(θ)R(\theta) in direction θ\theta: it extends farthest along the line of q1\vb{q}_1, and angles where RR is negative, around q2\vb{q}_2, appear in blue (a negative radius is drawn toward the opposite side). Below, R(θ)R(\theta) oscillates between λ2\lambda_2 and λ1\lambda_1, with extrema exactly at the eigenvector angles, where the purple arrow disappears.
ProofThe maximum of a quadratic form on the sphere
Prove: If A\mat{A} is symmetric with eigenvalues λ1≥⋯≥λn\lambda_1 \ge \dots \ge \lambda_n, then max⁡∥x∥=1x⊤Ax=λ1\max_{\norm{\vb{x}} = 1} \vb{x}\T\mat{A}\vb{x} = \lambda_1.
0
Write A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T with Q\mat{Q} orthogonal and Λ=diag⁡(λ1,…,λn)\mat{\Lambda} = \diag(\lambda_1, \dots, \lambda_n).

Step 1 of 4. Change variables, y=Q⊤x\vb{y} = \mat{Q}\T\vb{x}. What happens to the constraint ∥x∥=1\norm{\vb{x}} = 1?

The gradient and quadratic accuracy

The Rayleigh quotient is differentiable away from the origin. Using ∇(x⊤Ax)=(A+A⊤)x=2Ax\grad(\vb{x}\T\mat{A}\vb{x}) = (\mat{A} + \mat{A}\T)\vb{x} = 2\mat{A}\vb{x} (this is where symmetry is used) and the quotient rule:

∇R(x)=(x⊤x) 2Ax−(x⊤Ax) 2x(x⊤x)2\grad R(\vb{x}) = \frac{(\vb{x}\T\vb{x})\,2\mat{A}\vb{x} - (\vb{x}\T\mat{A}\vb{x})\,2\vb{x}}{(\vb{x}\T\vb{x})^2}
Quotient rule with the gradients of the numerator and denominator.
1/3

The vector Ax−R(x)x\mat{A}\vb{x} - R(\vb{x})\vb{x} is the purple arrow in the interactive: the part of Ax\mat{A}\vb{x} perpendicular to x\vb{x}. Eigenvectors are the only critical points of RR; those of λ1\lambda_1 and λn\lambda_n give the maximum and minimum, and the intermediate ones are saddle points of RR on the sphere (in R3\R^3, q2\vb{q}_2 is a maximum of RR in the direction of q3\vb{q}_3 and a minimum in that of q1\vb{q}_1).

The fact that q1\vb{q}_1 is a critical point has a valuable numerical consequence. If x=cos⁡t q1+sin⁡t u\vb{x} = \cos t\,\vb{q}_1 + \sin t\,\vb{u} with u⊥q1\vb{u} \perp \vb{q}_1 a unit vector, that is, if x\vb{x} makes an angle tt with the eigenvector, then

λ1−R(x)=(λ1−R(u))sin⁡2t≤(λ1−λn) sin⁡2t.\lambda_1 - R(\vb{x}) = \big(\lambda_1 - R(\vb{u})\big)\sin^2 t \le (\lambda_1 - \lambda_n)\,\sin^2 t .

An error of order tt in the vector produces an error of order t2t^2 in the estimated eigenvalue. This is why the Rayleigh quotient is the natural eigenvalue estimator in power iteration and Rayleigh quotient inverse iteration.

Courant–Fischer: each eigenvalue as an optimization problem

Rayleigh characterizes λ1\lambda_1 and λn\lambda_n. For the intermediate eigenvalues, the idea is to restrict RR to subspaces. If x\vb{x} ranges over a subspace SS of dimension kk, the minimum of RR on SS is at most λk\lambda_k; and there is an SS (the span of q1,…,qk\vb{q}_1, \dots, \vb{q}_k) where it equals exactly λk\lambda_k.

This is the Courant–Fischer min-max theorem.

Proof

First equality. There is an SS attaining λk\lambda_k. With Sk=span⁡{q1,…,qk}S_k = \spn\{\vb{q}_1, \dots, \vb{q}_k\}, every x∈Sk\vb{x} \in S_k has zero eigenvector coordinates from k+1k + 1 onward, so R(x)R(\vb{x}) is an average of λ1,…,λk\lambda_1, \dots, \lambda_k, all ≥λk\ge \lambda_k. The minimum on SkS_k is λk\lambda_k (at qk\vb{q}_k), so the maximum over all SS is ≥λk\ge \lambda_k.

No SS exceeds λk\lambda_k. Let SS be any subspace of dimension kk and T=span⁡{qk,…,qn}T = \spn\{\vb{q}_k, \dots, \vb{q}_n\} of dimension n−k+1n - k + 1. Since dim⁡S+dim⁡T=n+1>n\dim S + \dim T = n + 1 > n, there is an x≠0\vb{x} \ne \vb{0} in S∩TS \cap T. That x\vb{x} is a combination of qk,…,qn\vb{q}_k, \dots, \vb{q}_n, so R(x)R(\vb{x}) is an average of λk,…,λn\lambda_k, \dots, \lambda_n, all ≤λk\le \lambda_k. Therefore min⁡SR≤R(x)≤λk\min_S R \le R(\vb{x}) \le \lambda_k.

The second equality is the first applied to −A-\mat{A}, whose eigenvalues in descending order are −λn≥⋯≥−λ1-\lambda_n \ge \dots \ge -\lambda_1.

∎

The first half of the proof is constructive and the second is a dimension argument: in Rn\R^n, a subspace of dimension kk and another of dimension n−k+1n - k + 1 always intersect. The interactive shows this in R3\R^3 with k=2k = 2, where the subspaces are planes.

InteractiveCourant–Fischer with planes in R3\R^3
Each point of the disk represents a plane SS through the origin, perpendicular to the normal n\vb{n} (viewed from above; the disk boundary represents vertical planes). In max-min mode, the color is the minimum of RR on SS. Drag n\vb{n} toward the highest value on the map (the right end of the color scale): the best minimum is exactly λ2\lambda_2 and is attained at n=q3\vb{n} = \vb{q}_3, that is, with S=span⁡{q1,q2}S = \spn\{\vb{q}_1, \vb{q}_2\}. Min-max mode seeks the lowest value: the smallest maximum is also λ2\lambda_2, at n=q1\vb{n} = \vb{q}_1. On the right, RR on the circle in the selected plane: its minimum μ2\mu_2 and maximum μ1\mu_1 always lie on opposite sides of the λ2\lambda_2 line. Move λ2\lambda_2 to λ3\lambda_3 in max-min mode (or to λ1\lambda_1 in min-max): with a double eigenvalue, every plane intersects its eigenspace and the entire map equals λ2\lambda_2.

The theorem’s power is that it characterizes λk\lambda_k without mentioning eigenvectors. Any trial subspace gives a bound: if you find an SS of dimension kk on which R≥cR \ge c, then λk≥c\lambda_k \ge c. The two most-used comparison results follow almost for free.

Proof

Since ∥Uz∥=∥z∥\norm{\mat{U}\vb{z}} = \norm{\vb{z}}, RB(z)=RA(Uz)R_{\mat{B}}(\vb{z}) = R_{\mat{A}}(\mat{U}\vb{z}). The subspaces of dimension kk of Rm\R^m become, on multiplying by U\mat{U}, some subspaces of dimension kk of Rn\R^n (those contained in col⁡(U)\col(\mat{U})). By Courant–Fischer, μk\mu_k is the maximum of the minimum of RAR_{\mat{A}} over these subspaces, a smaller family than all subspaces: μk≤λk\mu_k \le \lambda_k. The min-max form similarly gives μk=min⁡dim⁡T=m−k+1max⁡RA≥min⁡dim⁡S=m−k+1max⁡RA=λn−(m−k+1)+1=λk+n−m\mu_k = \min_{\dim T = m-k+1}\max R_{\mat{A}} \ge \min_{\dim S = m-k+1}\max R_{\mat{A}} = \lambda_{n-(m-k+1)+1} = \lambda_{k+n-m}.

∎

Interlacing explains, for example, why Ritz values computed by Lanczos on a Krylov subspace never exceed the true extreme eigenvalues, and why removing a graph node cannot move eigenvalues of its adjacency matrix (which loses a row and a column) beyond the gaps between consecutive eigenvalues.

The proof is a guided exercise at the end of the lesson: RA+E=RA+RER_{\mat{A}+\mat{E}} = R_{\mat{A}} + R_{\mat{E}}, and RER_{\mat{E}} lies between λn(E)\lambda_n(\mat{E}) and λ1(E)\lambda_1(\mat{E}). The second form uses the fact that for a symmetric matrix the spectral norm is ∥E∥2=max⁡i∣λi(E)∣\norm{\mat{E}}_2 = \max_i\abs{\lambda_i(\mat{E})}.

Weyl says the eigenvalues of a symmetric matrix are 1-Lipschitz functions of the matrix: their condition number is 1, the best possible. For an arbitrary matrix this is completely false. [01ε0]\begin{bmatrix} 0 & 1 \\ \eps & 0 \end{bmatrix} has eigenvalues ±ε\pm\sqrt{\eps}: a perturbation of 10−1010^{-10} in one entry moves the eigenvalues 10−510^{-5}, a hundred thousand times more. A Jordan block n×nn\times n turns ε\eps into ε1/n\eps^{1/n}.

Perturbation: stable eigenvalues, fragile eigenvectors

If eigenvalues move so little, do eigenvectors also move little? Not necessarily. The extreme case is A=I\mat{A} = \mat{I}: every vector is an eigenvector, and the eigenvectors of I+E\mat{I} + \mat{E} are those of E\mat{E}, which can point anywhere however small E\mat{E} is. A less extreme case:

A=[1+δ001],E=[0εε0].\mat{A} = \begin{bmatrix} 1 + \delta & 0 \\ 0 & 1 \end{bmatrix}, \qquad \mat{E} = \begin{bmatrix} 0 & \eps \\ \eps & 0 \end{bmatrix}.

The eigenvectors of A+E\mat{A} + \mat{E} make an angle θ\theta with the axes, with tan⁡2θ=2ε/δ\tan 2\theta = 2\eps/\delta. With δ=0.01\delta = 0.01 and ε=0.001\eps = 0.001, the eigenvalues move about 10−410^{-4} (of order ε2/δ\eps^2/\delta, well below Weyl’s bound), but the eigenvectors rotate 5.65°5.65°. The rotation depends on the ratio of perturbation size to the spectral gap, the distance from the eigenvalue to the others.

Proof

Since A^q^j=λ^jq^j\hat{\mat{A}}\hat{\vb{q}}_j = \hat\lambda_j\hat{\vb{q}}_j, the residual of q^j\hat{\vb{q}}_j as an eigenvector of A\mat{A} is r=Aq^j−λ^jq^j=−Eq^j\vb{r} = \mat{A}\hat{\vb{q}}_j - \hat\lambda_j\hat{\vb{q}}_j = -\mat{E}\hat{\vb{q}}_j, and ∥r∥≤∥E∥2\norm{\vb{r}} \le \norm{\mat{E}}_2. Write q^j=∑iciqi\hat{\vb{q}}_j = \sum_i c_i\vb{q}_i; then r=∑i(λi−λ^j)ciqi\vb{r} = \sum_i(\lambda_i - \hat\lambda_j)c_i\vb{q}_i and

∥r∥2=∑i(λi−λ^j)2ci2≥min⁡i≠j(λi−λ^j)2∑i≠jci2=min⁡i≠j(λi−λ^j)2 sin⁡2θ.\norm{\vb{r}}^2 = \sum_i(\lambda_i - \hat\lambda_j)^2c_i^2 \ge \min_{i\ne j}(\lambda_i - \hat\lambda_j)^2\sum_{i \ne j}c_i^2 = \min_{i\ne j}(\lambda_i - \hat\lambda_j)^2\,\sin^2\theta .

By Weyl, ∣λ^j−λj∣≤∥E∥2\abs{\hat\lambda_j - \lambda_j} \le \norm{\mat{E}}_2, so ∣λi−λ^j∣≥δj−∥E∥2\abs{\lambda_i - \hat\lambda_j} \ge \delta_j - \norm{\mat{E}}_2 for i≠ji \ne j. If ∥E∥2≤δj/2\norm{\mat{E}}_2 \le \delta_j/2, this is ≥δj/2\ge \delta_j/2 and gives sin⁡θ≤2∥E∥2/δj\sin\theta \le 2\norm{\mat{E}}_2/\delta_j. If ∥E∥2>δj/2\norm{\mat{E}}_2 > \delta_j/2, the bound is greater than 1 and holds trivially.

∎

Davis and Kahan (1970) proved the subspace version: if a group of eigenvalues is separated from the rest by a gap δ\delta, the invariant subspace spanned by their eigenvectors rotates, in the sense of principal angles, at most on the order of ∥E∥/δ\norm{\mat{E}}/\delta. The form with factor 2 and the gap of A\mat{A} (rather than that of the perturbed matrix) is from Yu, Wang and Samworth (2015). In practice, individual vectors within a group of nearly equal eigenvalues are unstable, but the subspace of the whole group is stable if well separated from the rest.

InteractiveStable eigenvalues, fragile eigenvectors
Sixty random symmetric perturbations with exactly ∥E∥2=ε\norm{\mat{E}}_2 = \varepsilon, plus the worst possible one (hollow circle and dashed line). Perturbed eigenvalues never leave the Weyl bands of width 2ε2\varepsilon, whatever the gap. Now decrease gg while keeping ε\varepsilon fixed: the fan of eigenvectors q^1\hat{\vb{q}}_1 opens, the worst case follows exactly 12arcsin⁡(2ε/g)\tfrac12\arcsin(2\varepsilon/g) (shaded wedge), and Davis–Kahan bounds it without ever being violated. When g<2εg \lt 2\varepsilon noise can swap the two eigenvalues and q^1\hat{\vb{q}}_1 may end up perpendicular to q1\vb{q}_1.

In 2×22\times 2 everything can be computed by hand. In the eigenbasis, A=diag⁡(λ1,λ2)\mat{A} = \diag(\lambda_1, \lambda_2), g=λ1−λ2g = \lambda_1 - \lambda_2, and every symmetric matrix of norm ε\eps with zero trace is E=[−abba]\mat{E} = \begin{bmatrix} -a & b \\ b & a \end{bmatrix} with a2+b2=ε2a^2 + b^2 = \eps^2 (the multiple of I\mat{I} moves eigenvalues but rotates nothing). The perturbed eigenvector angle satisfies tan⁡2θ=2b/(g−2a)\tan 2\theta = 2b/(g - 2a): the point (g−2a,2b)(g - 2a, 2b) traces a circle of radius 2ε2\eps centered at (g,0)(g, 0), and the largest angle with the axis is attained at the tangent, with sin⁡2θ=2ε/g\sin 2\theta = 2\eps/g. This is the wedge in the interactive. For small ε\eps, θ≈ε/g\theta \approx \eps/g, half what Davis–Kahan allows.

The consequences appear as soon as you work with data:

  • PCA. If two principal variances are nearly equal, the two corresponding components are not identified: with another sample of the same data they will be rotated within their plane. The plane itself is well estimated.
  • Spectral clustering. The number of groups is chosen by seeking a large gap in the Laplacian spectrum (the eigengap heuristic): the gap makes the eigenvectors used for grouping stable.
  • Gradients of eigh. The derivative of eigenvectors with respect to the matrix contains factors 1/(λi−λj)1/(\lambda_i - \lambda_j); the documentation for torch.linalg.eigh warns that the gradient is numerically unstable when two eigenvalues are close. It is the same phenomenon.
  • Tests. Comparing eigenvectors between implementations makes sense only when eigenvalues are well separated, and even then only up to sign. For repeated or nearly repeated eigenvalues compare projectors.

The next two experiments measure the bounds in dimension 30. Random perturbations remain far from the worst case (in high dimensions a random direction barely aligns with those that matter), so the adversarial perturbation is also included: the one that makes each bound hold with equality or nearly so.

[ ]Weyl in actionBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(1)
n = 30

def ortogonal_aleatoria(n, rng):
    Q, R = np.linalg.qr(rng.standard_normal((n, n)))
    return Q * np.sign(np.diag(R))

def ruido_simetrico(n, eps, rng):
    """Matriz simétrica aleatoria con norma espectral exactamente eps."""
    G = rng.standard_normal((n, n))
    E = (G + G.T) / 2
    return eps * E / np.max(np.abs(np.linalg.eigvalsh(E)))   # ‖E‖₂ = máx |λᵢ(E)|

Q = ortogonal_aleatoria(n, rng)
lam = np.linspace(3, -3, n)                  # orden decreciente, como en el texto
A = Q @ np.diag(lam) @ Q.T

eps_lista = np.logspace(-4, 0, 7)
azar, adversaria = [], []
for eps in eps_lista:
    desv = [np.max(np.abs(np.linalg.eigvalsh(A + ruido_simetrico(n, eps, rng))[::-1] - lam)) for _ in range(8)]
    azar.append(max(desv))
    E = eps * np.outer(Q[:, 0], Q[:, 0])     # empuja el mayor autovalor en su propia dirección
    adversaria.append(np.max(np.abs(np.linalg.eigvalsh(A + E)[::-1] - lam)))

for eps, d1, d2 in zip(eps_lista, azar, adversaria):
    print(f"‖E‖₂ = {eps:.0e}   al azar: {d1/eps:.2f}·‖E‖   adversaria: {d2/eps:.2f}·‖E‖")

fig, ax = plt.subplots(figsize=(6, 3.8))
ax.loglog(eps_lista, eps_lista, "--", color="gray", label="cota de Weyl: ‖E‖₂")
ax.loglog(eps_lista, adversaria, "s", label="perturbación adversaria")
ax.loglog(eps_lista, azar, "o", label="peor de 8 al azar")
ax.set_xlabel("‖E‖₂"); ax.set_ylabel("máx_k |λ_k(A+E) − λ_k(A)|"); ax.legend()
plt.show()
[ ]Davis–Kahan in actionBrowser
eps = 1e-2
huecos = np.logspace(-3, 0, 13)
seno_azar, seno_adv = [], []
for g in huecos:
    lam = np.concatenate([[1 + g, 1.0], np.linspace(0.5, -1, n - 2)])
    A = Q @ np.diag(lam) @ Q.T
    q1 = Q[:, 0]
    s = []
    for _ in range(10):
        w, V = np.linalg.eigh(A + ruido_simetrico(n, eps, rng))
        s.append(np.sqrt(max(0.0, 1 - (V[:, -1] @ q1) ** 2)))
    seno_azar.append(max(s))
    # adversaria: acopla q1 con q2, la dirección más cercana en el espectro
    E = eps * (np.outer(Q[:, 0], Q[:, 1]) + np.outer(Q[:, 1], Q[:, 0]))
    w, V = np.linalg.eigh(A + E)
    seno_adv.append(np.sqrt(max(0.0, 1 - (V[:, -1] @ q1) ** 2)))

fig, ax = plt.subplots(figsize=(6, 3.8))
ax.loglog(huecos, np.minimum(1, 2 * eps / huecos), "--", color="gray", label="Davis-Kahan: 2ε/hueco")
ax.loglog(huecos, seno_adv, "s", label="perturbación adversaria")
ax.loglog(huecos, seno_azar, "o", label="peor de 10 al azar")
ax.set_xlabel("hueco λ₁ − λ₂"); ax.set_ylabel("sen θ(q̂₁, q₁)"); ax.legend()
plt.show()
print("con hueco 0.001, la adversaria gira q₁", round(np.degrees(np.arcsin(seno_adv[0])), 1), "grados")

In both plots the points lie below the dashed line. The adversarial perturbation reaches Weyl’s bound exactly and comes within a factor of 2 of Davis–Kahan’s (the θ≈ε/g\theta \approx \eps/g of the 2×22\times 2 case): the bounds cannot be improved beyond a constant. With random perturbation, by contrast, the eigenvalue moves much less than ∥E∥2\norm{\mat{E}}_2: Weyl is a worst-case bound, not a prediction of the typical case.

Implementation: Jacobi’s method

Jacobi’s method diagonalizes a symmetric matrix by applying rotations on both sides. It uses the same Givens rotations as the QR lesson, but now as similarities: A←J⊤AJ\mat{A} \leftarrow \mat{J}\T\mat{A}\mat{J}, preserving eigenvalues and symmetry. Each rotation acts in a coordinate plane (p,q)(p, q) and is chosen to zero the pair of entries apq=aqpa_{pq} = a_{qp}.

The rotation. J\mat{J} is the identity except for jpp=jqq=cj_{pp} = j_{qq} = c, jpq=sj_{pq} = s, jqp=−sj_{qp} = -s, with c2+s2=1c^2 + s^2 = 1. In B=J⊤AJ\mat{B} = \mat{J}\T\mat{A}\mat{J} only rows and columns pp and qq change, and the entry we want to zero is

bpq=apq(c2−s2)+(app−aqq) cs.b_{pq} = a_{pq}(c^2 - s^2) + (a_{pp} - a_{qq})\,cs .

Dividing by apqc2a_{pq}c^2 and writing t=s/ct = s/c (the tangent of the angle), bpq=0b_{pq} = 0 is equivalent to

t2+2τt−1=0,τ=aqq−app2apq.t^2 + 2\tau t - 1 = 0, \qquad \tau = \frac{a_{qq} - a_{pp}}{2a_{pq}} .

Of the two roots, take the one with smaller magnitude, t=sgn⁡(τ)/(∣τ∣+1+τ2)t = \operatorname{sgn}(\tau)/(\abs{\tau} + \sqrt{1 + \tau^2}), corresponding to an angle of at most 45°45° and computed without subtracting similar numbers. Then, c=1/1+t2c = 1/\sqrt{1 + t^2} and s=tcs = tc.

Why it converges. Call the off-diagonal mass off⁡(A)2=∑i≠jaij2\operatorname{off}(\mat{A})^2 = \sum_{i \ne j}a_{ij}^2. The Frobenius norm does not change under orthogonal similarity, and within the 2×22\times 2 block being diagonalized, the mass 2apq22a_{pq}^2 moves entirely to the diagonal; the other entries of rows pp and qq merely rotate in pairs and preserve their sum of squares. Thus each rotation satisfies exactly

off⁡(B)2=off⁡(A)2−2apq2.\operatorname{off}(\mat{B})^2 = \operatorname{off}(\mat{A})^2 - 2a_{pq}^2 .

The zeros created by one rotation are disturbed by the next, but the off-diagonal mass only decreases. If the largest entry in magnitude is chosen each time (classical Jacobi), since there are n(n−1)n(n-1) off-diagonal entries, 2apq2≥2off⁡(A)2/(n(n−1))2a_{pq}^2 \ge 2\operatorname{off}(\mat{A})^2/(n(n-1)) and off⁡2\operatorname{off}^2 decreases at least geometrically. In practice all pairs are visited in fixed order (cyclic Jacobi; each complete pass is a sweep) and, when the matrix is already close to diagonal, convergence is quadratic: each sweep squares the relative size of what remains off the diagonal.

The eigenvectors. The product of all rotations, V=J1J2⋯\mat{V} = \mat{J}_1\mat{J}_2\cdots, satisfies V⊤AV→Λ\mat{V}\T\mat{A}\mat{V} \to \mat{\Lambda}, so its columns are the eigenvectors, orthonormal by construction.

[ ]Jacobi from scratchBrowser
import numpy as np
import matplotlib.pyplot as plt

def off(A):
    """Norma de Frobenius de la parte fuera de la diagonal."""
    return np.linalg.norm(A - np.diag(np.diag(A)))

def sym_schur2(A, p, q):
    """(c, s) de la rotación que anula A[p, q] en J^T A J."""
    if A[p, q] == 0.0:
        return 1.0, 0.0
    tau = (A[q, q] - A[p, p]) / (2.0 * A[p, q])
    if tau >= 0:
        t = 1.0 / (tau + np.sqrt(1.0 + tau * tau))
    else:
        t = -1.0 / (-tau + np.sqrt(1.0 + tau * tau))
    c = 1.0 / np.sqrt(1.0 + t * t)
    return c, t * c

def rotar(A, V, p, q, c, s):
    """A <- J^T A J y V <- V J, tocando solo las filas y columnas p y q."""
    Ap, Aq = A[:, p].copy(), A[:, q].copy()
    A[:, p], A[:, q] = c * Ap - s * Aq, s * Ap + c * Aq
    Ap, Aq = A[p, :].copy(), A[q, :].copy()
    A[p, :], A[q, :] = c * Ap - s * Aq, s * Ap + c * Aq
    Vp, Vq = V[:, p].copy(), V[:, q].copy()
    V[:, p], V[:, q] = c * Vp - s * Vq, s * Vp + c * Vq

def jacobi(A, tol=1e-12, max_barridos=30):
    A = np.array(A, dtype=float)
    n = A.shape[0]
    V = np.eye(n)
    escala = np.linalg.norm(A)
    historia = [off(A)]
    for _ in range(max_barridos):
        if historia[-1] <= tol * escala:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                c, s = sym_schur2(A, p, q)
                rotar(A, V, p, q, c, s)
        historia.append(off(A))
    w = np.diag(A).copy()
    orden = np.argsort(w)
    return w[orden], V[:, orden], historia

rng = np.random.default_rng(0)
M = rng.standard_normal((8, 8))
A = (M + M.T) / 2
w, Q, historia = jacobi(A)
for k, h in enumerate(historia):
    print(f"barrido {k}: off(A) = {h:.2e}")
print("‖QΛQᵀ − A‖ =", np.linalg.norm(Q @ np.diag(w) @ Q.T - A))
print("‖QᵀQ − I‖  =", np.linalg.norm(Q.T @ Q - np.eye(8)))
print("máx |λ − λ_eigh| =", np.max(np.abs(w - np.linalg.eigvalsh(A))))

# la identidad off(B)² = off(A)² − 2 a_pq² en una sola rotación
B, V = A.copy(), np.eye(8)
antes, apq = off(B) ** 2, B[2, 5]
c, s = sym_schur2(B, 2, 5)
rotar(B, V, 2, 5, c, s)
print("caída de off² en una rotación:", antes - off(B) ** 2, " 2·a_pq² =", 2 * apq ** 2)

fig, ax = plt.subplots(figsize=(6, 3.5))
ax.semilogy(range(len(historia)), np.maximum(historia, 1e-17), "o-")
ax.set_xlabel("barrido"); ax.set_ylabel("off(A)")
plt.show()

Look at the off(A) column: after a few slow sweeps, the exponent doubles each time (something like 10−410^{-4}, 10−1010^{-10}, 10−1610^{-16}). This is quadratic convergence. Notice also how off is computed: by subtracting the diagonal and taking the norm of what remains. The apparently equivalent formula ∥A∥F2−∑iaii2\sqrt{\norm{\mat{A}}_F^2 - \sum_i a_{ii}^2} subtracts two nearly equal numbers when the matrix is nearly diagonal and cannot go below u ∥A∥F≈10−8∥A∥F\sqrt{u}\,\norm{\mat{A}}_F \approx 10^{-8}\norm{\mat{A}}_F, so the stopping criterion would never see the last sweeps.

With the decomposition in hand, the quadratic form’s level curves can be drawn directly: the ellipse q=1q = 1 is the image of the unit circle under Q diag⁡(1/λi)\mat{Q}\,\diag(1/\sqrt{\lambda_i}).

[ ]Level curves from the decompositionBrowser
A2 = np.array([[5.0, 2.0], [2.0, 2.0]])
w2, Q2, _ = jacobi(A2)
print("autovalores:", w2)                          # 1 y 6
t = np.linspace(0, 2 * np.pi, 200)
elipse = Q2 @ np.diag(1 / np.sqrt(w2)) @ np.vstack([np.cos(t), np.sin(t)])

X, Y = np.meshgrid(np.linspace(-1.6, 1.6, 300), np.linspace(-1.6, 1.6, 300))
Z = A2[0, 0] * X**2 + 2 * A2[0, 1] * X * Y + A2[1, 1] * Y**2
fig, ax = plt.subplots(figsize=(4.6, 4.6))
ax.contour(X, Y, Z, levels=[0.25, 1, 2.25, 4], colors="gray", linewidths=1)
ax.plot(elipse[0], elipse[1], lw=2.5, label="Q·diag(1/√λ)·círculo")
for i in range(2):
    v = Q2[:, i] / np.sqrt(w2[i])
    ax.annotate("", xy=v, xytext=(0, 0), arrowprops=dict(arrowstyle="->", lw=2))
ax.set_aspect("equal"); ax.legend(loc="lower right")
plt.show()

The professional version: eigh and company

ToolWhat it doesWhen
np.linalg.eigh(A)all eigenvalues (ascending) and orthonormal eigenvectorsdense symmetric or Hermitian matrices
np.linalg.eigvalsh(A)eigenvalues only, cheaperspectrum, inertia, condition number
scipy.linalg.eigh(A, subset_by_index=[i, j])only eigenvalues with indices ii to jjthe largest kk of a dense matrix
scipy.linalg.eigh(A, B)generalized problem Ax=λBx\mat{A}\vb{x} = \lambda\mat{B}\vb{x}with B\mat{B} positive definite (next lesson)
scipy.sparse.linalg.eigsh(A, k)kk eigenpairs by Lanczos (ARPACK)large sparse matrices
torch.linalg.eigh(A)the same on GPU, batched and differentiableinside a model

The important point is what eigh assumes. It reads only one triangle of the matrix (the lower one, by default UPLO='L') and assumes the other mirrors it. If you pass a matrix that is not symmetric, it gives no warning: it computes the eigenvalues of a different matrix. And if a matrix is symmetric in theory but not exactly so due to rounding, eig treats it as general: it may return complex type, unordered eigenvalues and, for repeated eigenvalues, eigenvectors that are not orthogonal.

[ ]eigh versus eigBrowser
import numpy as np
import scipy.linalg as sla

rng = np.random.default_rng(0)
Q, _ = np.linalg.qr(rng.standard_normal((5, 5)))
A = Q @ np.diag([1.0, 1.0, 1.0, 2.0, 3.0]) @ Q.T
print("¿simétrica exacta?", np.array_equal(A, A.T), "  máx |A − Aᵀ| =", np.abs(A - A.T).max())

w, V = np.linalg.eig(A)
print("eig :", np.round(w, 12), " tipo:", w.dtype)
print("eig : ‖VᵀV − I‖ =", np.linalg.norm(V.T @ V - np.eye(5)))
w, V = np.linalg.eigh(A)
print("eigh:", w)
print("eigh: ‖VᵀV − I‖ =", np.linalg.norm(V.T @ V - np.eye(5)))

# eigh solo lee el triángulo inferior: con una matriz no simétrica, responde otra pregunta
B = np.array([[2.0, 100.0],
              [1.0, 2.0]])
print("autovalores de B:", np.linalg.eigvals(B).real, "   eigh(B) dice:", np.linalg.eigvalsh(B))

# la cura: simetrizar explícitamente lo que solo es simétrico salvo redondeo
As = (A + A.T) / 2
print("¿simétrica tras simetrizar?", np.array_equal(As, As.T))

# solo los dos mayores, sin calcular el resto
print("dos mayores:", sla.eigh(As, subset_by_index=[3, 4], eigvals_only=True))

The first matrix is symmetric apart from errors of order 10−1610^{-16} and has a triple eigenvalue; see how far the V⊤V\mat{V}\T\mat{V} of eig is from the identity: within the three-dimensional eigenspace it chooses vectors that need not be orthogonal. The second has eigenvalues 1212 and −8-8, and eigh calmly returns 11 and 33, which belong to [2112]\begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}.

For large sparse matrices, only a few eigenpairs are computed with Krylov methods. The Laplacian of a path with nn nodes has known eigenvalues, 2−2cos⁡(πk/n)2 - 2\cos(\pi k/n) for k=0,…,n−1k = 0, \dots, n - 1, so it can check eigsh. For the smallest eigenvalues use shift-invert mode (sigma), which factorizes L−σI\mat{L} - \sigma\mat{I} once and applies Lanczos to its inverse, where those eigenvalues become the largest.

[ ]Small Laplacian eigenvalues with eigshBrowser
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh

n = 400
diag = np.r_[1.0, 2.0 * np.ones(n - 2), 1.0]
L = sp.diags([diag, -np.ones(n - 1), -np.ones(n - 1)], [0, -1, 1], format="csc")
vals = np.sort(eigsh(L, k=5, sigma=-1e-3, which="LM", return_eigenvectors=False))
exactos = 2 - 2 * np.cos(np.pi * np.arange(5) / n)
print("eigsh  :", vals)
print("exactos:", exactos)
print("error máximo:", np.max(np.abs(vals - exactos)))

Common mistakes

Exercises

QuizClassifying by inertia
How would you classify the quadratic form q(x)=x12+x22+x32+4x1x2+4x1x3+4x2x3q(\vb{x}) = x_1^2 + x_2^2 + x_3^2 + 4x_1x_2 + 4x_1x_3 + 4x_2x_3 on R3\R^3?
NumericThe maximum on the circle
Find the maximum of 3x2+2xy+3y23x^2 + 2xy + 3y^2 on the unit circle x2+y2=1x^2 + y^2 = 1.
NumericArea of a tilted ellipse
Find the area of the region 2x2+2xy+3y2≤12x^2 + 2xy + 3y^2 \le 1.
QuizPositive eigenvalues, indefinite form
Both eigenvalues of M=[1401]\mat{M} = \begin{bmatrix} 1 & 4 \\ 0 & 1 \end{bmatrix} equal 1. What can you say about q(x)=x⊤Mxq(\vb{x}) = \vb{x}\T\mat{M}\vb{x}?
NumericA tilted vector, an almost exact eigenvalue
A\mat{A} is a symmetric 2×22\times 2 matrix with eigenvalues λ1=4\lambda_1 = 4 and λ2=2\lambda_2 = 2. You take a unit vector x\vb{x} at an angle of 0.10.1 radians to q1\vb{q}_1. What is the error λ1−R(x)\lambda_1 - R(\vb{x})?
NumericCount eigenvalues without computing them
For a symmetric matrix A∈R4×4\mat{A} \in \R^{4\times 4}, Gaussian elimination without exchanges applied to A−2I\mat{A} - 2\mat{I} ends with pivots 3,−1,0.5,23, -1, 0.5, 2. How many eigenvalues of A\mat{A} are greater than 2?
QuizInterlacing
A symmetric A∈R3×3\mat{A} \in \R^{3\times 3} has eigenvalues 5,2,−15, 2, -1. Which pairs (μ1,μ2)(\mu_1, \mu_2) can be eigenvalues of a 2×22\times 2 principal submatrix of such a matrix?

More than one answer may be correct.

NumericHow far can an eigenvalue rise?
A\mat{A} is symmetric with eigenvalues 5,3,15, 3, 1 and E\mat{E} is symmetric with all its eigenvalues in [−0.2,0.5][-0.2, 0.5]. What is the largest possible value of λ2(A+E)\lambda_2(\mat{A} + \mat{E})?
QuizWhich components are reliable?
An estimated covariance has eigenvalues 5.05.0, 4.84.8 and 1.01.0, and its error relative to the true covariance satisfies ∥E∥2≤0.05\norm{\mat{E}}_2 \le 0.05. Which claim is justified?
ProofWeyl's inequality
Prove: If A\mat{A} and E\mat{E} are symmetric, λk(A+E)≤λk(A)+λ1(E)\lambda_k(\mat{A} + \mat{E}) \le \lambda_k(\mat{A}) + \lambda_1(\mat{E}) for every kk.
0
Order the eigenvalues from largest to smallest and use the Courant–Fischer max-min form: λk(M)=max⁡dim⁡S=kmin⁡x∈S∖{0}RM(x)\lambda_k(\mat{M}) = \max_{\dim S = k}\min_{\vb{x}\in S\setminus\{\vb{0}\}} R_{\mat{M}}(\vb{x}).

Step 1 of 4. How are the Rayleigh quotients of A+E\mat{A} + \mat{E}, A\mat{A} and E\mat{E} related?

Codejacobi_eigh from scratch
Implement jacobi_eigh(A, tol=1e-12) using cyclic Jacobi, without any NumPy or SciPy eigenvalue functions. It must return (w, Q): eigenvalues in ascending order and an orthogonal Q with A=Q diag⁡(w) Q⊤\mat{A} = \mat{Q}\,\diag(\vb{w})\,\mat{Q}\T, without modifying A. Stop when off⁡(A)≤tol⋅∥A∥F\operatorname{off}(\mat{A}) \le \texttt{tol}\cdot\norm{\mat{A}}_F. The tests use matrices with repeated eigenvalues: their eigenvectors are not unique, so reconstruction, orthogonality, and projectors onto eigenspaces are checked.
import numpy as np

def jacobi_eigh(A, tol=1e-12):
  A = np.array(A, dtype=float)
  n = A.shape[0]
  V = np.eye(n)
  # tu código: barridos sobre todas las parejas (p, q) con p < q,
  # rotación que anula A[p, q], acumulada en V
  ...
Shift+Enter to run

Summary

  • A real matrix is symmetric if and only if it diagonalizes in an orthonormal basis: A=QΛQ⊤=∑iλiqiqi⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T = \sum_i\lambda_i\vb{q}_i\vb{q}_i\T, with real eigenvalues and orthogonal Q\mat{Q}. The proof only needs q1⊥\vb{q}_1^\perp to be invariant, and that is symmetry.
  • A quadratic form x⊤Ax\vb{x}\T\mat{A}\vb{x} is, in eigenvector axes, ∑iλiyi2\sum_i\lambda_iy_i^2: eigenvectors give the axes, 1/∣λi∣1/\sqrt{\abs{\lambda_i}} the semiaxes of level 1, and eigenvalue signs (the inertia, invariant under congruence) decide between bowl, saddle, and channel.
  • The Rayleigh quotient is a weighted average of eigenvalues: its maximum is λ1\lambda_1, its minimum λn\lambda_n, its critical points are eigenvectors, and its eigenvalue estimate has error quadratic in vector error.
  • Courant–Fischer turns each λk\lambda_k into a max-min problem over subspaces, yielding Cauchy interlacing and Weyl’s inequality.
  • For computation: eigh, never eig, with the matrix symmetrized; Jacobi’s method teaches how to diagonalize using rotations and converges quadratically.
Key idea
The eigenvalues of a symmetric matrix are as stable as possible: noise E\mat{E} moves them by at most ∥E∥2\norm{\mat{E}}_2. Their eigenvectors are stable only if the spectral gap is large compared to that noise, and when it is not, the subspace can be estimated reliably, not the individual vectors.