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.
In the previous two lessons, the eigenvectors of an arbitrary matrix caused plenty of trouble. A rotation of the plane (except for 0° and 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 amplifies any rounding error.
Now look at where the matrices you diagonalize in practice come from:
Covariances.Σ=E[(x−μ)(x−μ)⊤] is an average of matrices vv⊤, each equal to its transpose. The covariance matrix is symmetric, and PCA diagonalizes it.
Hessians. If f has continuous second derivatives, ∂i∂jf=∂j∂if (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 in the normal equations, or a kernel matrix Kij=k(xi,xj): entries that are inner products, symmetric by definition.
Graph Laplacians.L=D−W with weights wij=wji. The Laplacian satisfies x⊤Lx=∑i<jwij(xi−xj)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⊤ with Qorthogonal. 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 formsx⊤Ax (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:
In 2×2, K=[0−kk0] is k times a rotation through −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=0 the two eigenlines are perpendicular and coincide with the axes of the ellipse: eigenvectors are the directions of maximum and minimum stretching. Increase k slowly: the eigenlines tilt toward each other, move away from the ellipse axes, and κ(V) grows; when k2 exceeds ((a−d)/2)2+s2 they merge and the eigenvalues become complex. Drag x around the circle: Ax is parallel to x only on the eigenlines.
What you just saw, with k=0, is the whole lesson in miniature:
The eigenvalues are real. The discriminant of [assd] is (a−d)2+4s2≥0, never negative. With the skew-symmetric part it becomes (a−d)2+4s2−4k2, which can be negative.
The eigenvectors are perpendicular and form an orthonormal basis: the change-of-basis matrix is a rotation (or reflection), with condition number 1.
The axes of the image ellipse are the eigenvectors, and its semiaxes measure ∣λ1∣ and ∣λ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 can be moved from one side of the inner product to the other.
Proof
(Ax)⊤y=x⊤A⊤y by the properties of the transpose, so if A⊤=A the two expressions coincide. Conversely, with x=ei and y=ej the equality says aji=aij.
∎
Proof
The characteristic polynomial has n roots in C. Let λ∈C be one of them and x∈Cn, x=0, with Ax=λx. Write xˉ for the entrywise conjugate and consider the number
s=xˉ⊤Ax.
On one hand, s=xˉ⊤(λx)=λxˉ⊤x=λ∑i∣xi∣2, and ∑i∣xi∣2>0 is real. On the other, since A is real, sˉ=x⊤Axˉ; that number is an 1×1 matrix, equal to its transpose: sˉ=xˉ⊤A⊤x=xˉ⊤Ax=s. Hence s is real, and so is λ=s/∑i∣xi∣2.
For the eigenvector: A−λ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 to close the chain sˉ=s. With a rotation the chain breaks and the complex eigenvalues e±iθ 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⊤, Ax=λx and Ay=μy with λ=μ, then x⊤y=0.
0
Let x,y∈Rn be nonzero and λ,μ 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⊤. The interesting one is the forward direction, proved by induction by removing one eigenvector at a time.
Proof
Induction on n. For n=1 there is nothing to prove. Assume the result holds in dimension n−1 and let A be symmetric n×n.
Step 1: an eigenvector. By the previous theorem, A has a real eigenvalue λ1 with a real eigenvector, which we normalize: Aq1=λ1q1, ∥q1∥=1.
Step 2: the complement is invariant. Let W=q1⊥ be the orthogonal complement of q1. If w∈W, then Aw∈W:
q1⊤(Aw)=(Aq1)⊤w=λ1q1⊤w=0.
The first equality is the self-adjointness lemma: this is where symmetry is used.
Step 3: reduce the dimension. Extend q1 to an orthonormal basis of Rn (using Gram–Schmidt, for example) and call U∈Rn×(n−1) the matrix of the n−1 new vectors, which are an orthonormal basis of W. The matrix Q1=[q1U] is orthogonal and
The lower-left block is U⊤(λ1q1)=0 because the columns of U are orthogonal to q1; the upper-right block is its transpose, because Q1⊤AQ1 is symmetric. And B∈R(n−1)×(n−1) is symmetric: B⊤=U⊤A⊤U=B.
Step 4: induction. By hypothesis, B=Q~Λ~Q~⊤ with Q~ orthogonal. Then
Q=Q1[100⊤Q~]
is a product of orthogonal matrices, hence orthogonal, and Q⊤AQ=diag(λ1,Λ~). Multiplying by Q on the left and Q⊤ on the right gives A=QΛQ⊤.
∎
Three consequences to keep in mind:
Multiplicities. If λ appears m times in Λ, its eigenspace has dimension m: for a symmetric matrix the geometric multiplicity always matches the algebraic multiplicity. There are never Jordan blocks.
Uniqueness.Λ is unique up to order. Q is not: each column can change sign, and if an eigenvalue is repeated m times, any orthonormal basis of its eigenspace works. This freedom causes the eigenvector fragility you will see later.
Hermitian version. If A∈Cn×n satisfies AH=A (conjugate transpose), the same proof with xˉ⊤ instead of x⊤ gives A=UΛUH with Uunitary and Λ 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⊤ column by row:
A=i=1∑nλiqiqi⊤.
Each qiqi⊤ is the orthogonal projection matrix onto the line of qi. The action of A on a vector has three stages:
Ax=i=1∑nλi(qi⊤x)qi:
compute the coordinates of x in the eigenbasis (Q⊤x), multiply each by its eigenvalue (Λ), and recombine (Q). A symmetric matrix is a collection of n independent stretches along n perpendicular directions.
Grouping repeated eigenvalues gives A=∑kμkPk, where μ1,…,μr are the distinct eigenvalues and Pk is the orthogonal projector onto the eigenspace of μk. This form is unique, even if Q is not, and the projectors satisfy
Pk2=Pk=Pk⊤,PkPl=0(k=l),k∑Pk=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⊤, for a polynomial, and by extension for any matrix function,
f(A)=i∑f(λi)qiqi⊤:
the inverse (f(λ)=1/λ, if no λi is zero), the exponentialetA 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∣ gives the best low-rank approximation, which for a symmetric matrix matches the one given by the SVD: its singular values are the ∣λ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 to be symmetric loses no generality. For any M, the skew-symmetric part contributes nothing: if K⊤=−K, the number x⊤Kx equals its transpose x⊤K⊤x=−x⊤Kx, so it is zero. Thus x⊤Mx=x⊤Sx with S=(M+M⊤)/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, a rotation (or reflection) that distorts nothing,
q(x)=x⊤QΛQ⊤x=y⊤Λy=λ1y12+λ2y22+⋯+λnyn2.
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.λ1y12+λ2y22=1 is an ellipse with semiaxes 1/λ1 along q1 and 1/λ2 along q2. The large eigenvalue gives the short semiaxis: where the form grows rapidly, level 1 is reached sooner. The enclosed area is π/λ1λ2=π/detA.
λ1>0>λ2. Hyperbolas. The zero level is the pair of lines y2=±λ1/∣λ2∣y1, separating the region where q>0 from the region where q<0.
λ1>0=λ2.λ1y12=1 consists of two lines parallel to q2: the form does not see direction q2 at all.
In the previous example, 5x2+4xy+2y2=1 is a tilted ellipse with semiaxis 1/6≈0.41 in direction (2,1) and semiaxis 1 in direction (−1,2).
InteractiveLevel curves of a quadratic form
Curves q=±0.25,±1,±2.25,… (positive in red, negative in blue; the q=±1 curves are thicker). Arrows show the semiaxes qi/∣λi∣ of level ±1. Decrease c from the bowl: when ac=b2 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 straightens the figure and the cross term disappears.
Classification and inertia
According to the signs taken by q(x) for x=0, the form (and its matrix) is positive definite if always q>0, positive semidefinite if always q≥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, positive semidefinite means all λi≥0, indefinite means eigenvalues of both signs. The triple (n+,n−,n0) giving the number of positive, negative, and zero eigenvalues is called the inertia of A. Positive definite matrices have their own lesson, the next one.
What if instead of Q you use an arbitrary change of variables, x=Sz with S invertible? The form now has matrix S⊤AS (a congruence, not a similarity), and its eigenvalues change. What does not change is their sign:
Proof
Let B=S⊤AS, and let p and p′ be the numbers of positive eigenvalues of A and B. Suppose p>p′. Let V+ be the span of the eigenvectors of A with positive eigenvalue: dimV+=p and x⊤Ax>0 for every nonzero x∈V+. Let Z be the span of the eigenvectors of B with eigenvalue ≤0: dimZ=n−p′ and z⊤Bz≤0 on Z. The space SZ has the same dimension, n−p′, and for x=Sz∈SZ, x⊤Ax=z⊤Bz≤0. Since dimV++dimSZ=p+n−p′>n, the two subspaces share a nonzero vector, on which q would be both >0 and ≤0. Contradiction. By symmetry (A=S−TBS−1), neither can p′>p hold. The same argument with −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⊤ with L unit lower triangular and 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] has pivots 1 and 1−4=−3: one positive eigenvalue and one negative (they are 3 and −1). Applied to A−σI, the number of negative pivots counts how many eigenvalues of A are less than σ, without computing any. This count and bisection in σ 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⋆ (zero gradient), the second-order Taylor expansion is
f(x⋆+h)≈f(x⋆)+21h⊤Hh,H=∇2f(x⋆),
and the local shape of f is that of the Hessian’s quadratic form. If 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 f 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 muchf curves in each eigenvector direction: the section of the surface along the line of qi is the parabola 21λit2. This is the information studied in a network’s Hessian spectrum.
InteractiveBowls, saddles, and channels
The surface z=x⊤Ax 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=λ1t2 and z=λ2t2. Set λ2 to zero (channel: a whole line of minima) and then negative (saddle). Turn on the surface in eigenvector axes to see that θ only rotates the figure. In the plane panel, apply the factors one by one: Q⊤ rotates the eigenvectors onto the axes, Λ stretches each axis by its eigenvalue, and Q undoes the rotation.
The Rayleigh quotient
From here on we order eigenvalues from largest to smallest, λ1≥λ2≥⋯≥λn (note: numpy.linalg.eigh returns them in ascending order).
R(cx)=R(x) for every c=0: only the direction of x matters, so it suffices to study it on the unit sphere, where R(x)=x⊤Ax. If x is an eigenvector, R(x) is its eigenvalue. For other vectors, in eigenvector coordinates y=Q⊤x,
The Rayleigh quotient is a weighted average of the eigenvalues, with weights equal to the squares of the coordinates of x in the eigenbasis. An average cannot exceed the largest value averaged or fall below the smallest:
InteractiveRayleigh on the circle
Move x around the circle. The magenta arrow is Ax, the gray arrow its shadow on x, measuring exactly R(x), and the purple arrow the remainder, Ax−R(x)x. The polar curve plots R(θ) in direction θ: it extends farthest along the line of q1, and angles where R is negative, around q2, appear in blue (a negative radius is drawn toward the opposite side). Below, R(θ) oscillates between λ2 and λ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 is symmetric with eigenvalues λ1≥⋯≥λn, then max∥x∥=1x⊤Ax=λ1.
0
Write A=QΛQ⊤ with Q orthogonal and Λ=diag(λ1,…,λn).
Step 1 of 4. Change variables, y=Q⊤x. What happens to the constraint ∥x∥=1?
The gradient and quadratic accuracy
The Rayleigh quotient is differentiable away from the origin. Using ∇(x⊤Ax)=(A+A⊤)x=2Ax (this is where symmetry is used) and the quotient rule:
∇R(x)=(x⊤x)2(x⊤x)2Ax−(x⊤Ax)2x
Quotient rule with the gradients of the numerator and denominator.
1/3
The vector Ax−R(x)x is the purple arrow in the interactive: the part of Ax perpendicular to x. Eigenvectors are the only critical points of R; those of λ1 and λn give the maximum and minimum, and the intermediate ones are saddle points of R on the sphere (in R3, q2 is a maximum of R in the direction of q3 and a minimum in that of q1).
The fact that q1 is a critical point has a valuable numerical consequence. If x=costq1+sintu with u⊥q1 a unit vector, that is, if x makes an angle t with the eigenvector, then
λ1−R(x)=(λ1−R(u))sin2t≤(λ1−λn)sin2t.
An error of order t in the vector produces an error of order t2 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 and λn. For the intermediate eigenvalues, the idea is to restrict R to subspaces. If x ranges over a subspace S of dimension k, the minimum of R on S is at most λk; and there is an S (the span of q1,…,qk) where it equals exactly λk.
This is the Courant–Fischer min-max theorem.
Proof
First equality. There is an S attaining λk. With Sk=span{q1,…,qk}, every x∈Sk has zero eigenvector coordinates from k+1 onward, so R(x) is an average of λ1,…,λk, all ≥λk. The minimum on Sk is λk (at qk), so the maximum over all S is ≥λk.
No S exceeds λk. Let S be any subspace of dimension k and T=span{qk,…,qn} of dimension n−k+1. Since dimS+dimT=n+1>n, there is an x=0 in S∩T. That x is a combination of qk,…,qn, so R(x) is an average of λk,…,λn, all ≤λk. Therefore minSR≤R(x)≤λk.
The second equality is the first applied to −A, whose eigenvalues in descending order are −λn≥⋯≥−λ1.
∎
The first half of the proof is constructive and the second is a dimension argument: in Rn, a subspace of dimension k and another of dimension n−k+1 always intersect. The interactive shows this in R3 with k=2, where the subspaces are planes.
InteractiveCourant–Fischer with planes in R3
Each point of the disk represents a plane S through the origin, perpendicular to the normal n (viewed from above; the disk boundary represents vertical planes). In max-min mode, the color is the minimum of R on S. Drag n toward the highest value on the map (the right end of the color scale): the best minimum is exactly λ2 and is attained at n=q3, that is, with S=span{q1,q2}. Min-max mode seeks the lowest value: the smallest maximum is also λ2, at n=q1. On the right, R on the circle in the selected plane: its minimum μ2 and maximum μ1 always lie on opposite sides of the λ2 line. Move λ2 to λ3 in max-min mode (or to λ1 in min-max): with a double eigenvalue, every plane intersects its eigenspace and the entire map equals λ2.
The theorem’s power is that it characterizes λk without mentioning eigenvectors. Any trial subspace gives a bound: if you find an S of dimension k on which R≥c, then λk≥c. The two most-used comparison results follow almost for free.
Proof
Since ∥Uz∥=∥z∥, RB(z)=RA(Uz). The subspaces of dimension k of Rm become, on multiplying by U, some subspaces of dimension k of Rn (those contained in col(U)). By Courant–Fischer, μk is the maximum of the minimum of RA over these subspaces, a smaller family than all subspaces: μk≤λk. The min-max form similarly gives μk=mindimT=m−k+1maxRA≥mindimS=m−k+1maxRA=λn−(m−k+1)+1=λ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+RE, and RE lies between λn(E) and λ1(E). The second form uses the fact that for a symmetric matrix the spectral norm is ∥E∥2=maxi∣λi(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. [0ε10] has eigenvalues ±ε: a perturbation of 10−10 in one entry moves the eigenvalues 10−5, a hundred thousand times more. A Jordan block n×n turns ε into ε1/n.
If eigenvalues move so little, do eigenvectors also move little? Not necessarily. The extreme case is A=I: every vector is an eigenvector, and the eigenvectors of I+E are those of E, which can point anywhere however small E is. A less extreme case:
A=[1+δ001],E=[0εε0].
The eigenvectors of A+E make an angle θ with the axes, with tan2θ=2ε/δ. With δ=0.01 and ε=0.001, the eigenvalues move about 10−4 (of order ε2/δ, well below Weyl’s bound), but the eigenvectors rotate 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, the residual of q^j as an eigenvector of A is r=Aq^j−λ^jq^j=−Eq^j, and ∥r∥≤∥E∥2. Write q^j=∑iciqi; then r=∑i(λi−λ^j)ciqi and
By Weyl, λ^j−λj≤∥E∥2, so λi−λ^j≥δj−∥E∥2 for i=j. If ∥E∥2≤δj/2, this is ≥δj/2 and gives sinθ≤2∥E∥2/δj. If ∥E∥2>δ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 δ, the invariant subspace spanned by their eigenvectors rotates, in the sense of principal angles, at most on the order of ∥E∥/δ. The form with factor 2 and the gap of 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.
Sixty random symmetric perturbations with exactly ∥E∥2=ε, plus the worst possible one (hollow circle and dashed line). Perturbed eigenvalues never leave the Weyl bands of width 2ε, whatever the gap. Now decrease g while keeping ε fixed: the fan of eigenvectors q^1 opens, the worst case follows exactly 21arcsin(2ε/g) (shaded wedge), and Davis–Kahan bounds it without ever being violated. When g<2ε noise can swap the two eigenvalues and q^1 may end up perpendicular to q1.
In 2×2 everything can be computed by hand. In the eigenbasis, A=diag(λ1,λ2), g=λ1−λ2, and every symmetric matrix of norm ε with zero trace is E=[−abba] with a2+b2=ε2 (the multiple of I moves eigenvalues but rotates nothing). The perturbed eigenvector angle satisfies tan2θ=2b/(g−2a): the point (g−2a,2b) traces a circle of radius 2ε centered at (g,0), and the largest angle with the axis is attained at the tangent, with sin2θ=2ε/g. This is the wedge in the interactive. For small ε, θ≈ε/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); 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 of the 2×2 case): the bounds cannot be improved beyond a constant. With random perturbation, by contrast, the eigenvalue moves much less than ∥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, preserving eigenvalues and symmetry. Each rotation acts in a coordinate plane (p,q) and is chosen to zero the pair of entries apq=aqp.
The rotation.J is the identity except for jpp=jqq=c, jpq=s, jqp=−s, with c2+s2=1. In B=J⊤AJ only rows and columns p and q change, and the entry we want to zero is
bpq=apq(c2−s2)+(app−aqq)cs.
Dividing by apqc2 and writing t=s/c (the tangent of the angle), bpq=0 is equivalent to
t2+2τt−1=0,τ=2apqaqq−app.
Of the two roots, take the one with smaller magnitude, t=sgn(τ)/(∣τ∣+1+τ2), corresponding to an angle of at most 45° and computed without subtracting similar numbers. Then, c=1/1+t2 and s=tc.
Why it converges. Call the off-diagonal mass off(A)2=∑i=jaij2. The Frobenius norm does not change under orthogonal similarity, and within the 2×2 block being diagonalized, the mass 2apq2 moves entirely to the diagonal; the other entries of rows p and q merely rotate in pairs and preserve their sum of squares. Thus each rotation satisfies exactly
off(B)2=off(A)2−2apq2.
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) off-diagonal entries, 2apq2≥2off(A)2/(n(n−1)) and off2 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⋯, satisfies V⊤AV→Λ, 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−4, 10−10, 10−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 subtracts two nearly equal numbers when the matrix is nearly diagonal and cannot go below u∥A∥F≈10−8∥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=1 is the image of the unit circle under Qdiag(1/λ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
Tool
What it does
When
np.linalg.eigh(A)
all eigenvalues (ascending) and orthonormal eigenvectors
dense symmetric or Hermitian matrices
np.linalg.eigvalsh(A)
eigenvalues only, cheaper
spectrum, inertia, condition number
scipy.linalg.eigh(A, subset_by_index=[i, j])
only eigenvalues with indices i to j
the largest k of a dense matrix
scipy.linalg.eigh(A, B)
generalized problem Ax=λBx
with B positive definite (next lesson)
scipy.sparse.linalg.eigsh(A, k)
k eigenpairs by Lanczos (ARPACK)
large sparse matrices
torch.linalg.eigh(A)
the same on GPU, batched and differentiable
inside a model
The important point is what eighassumes. 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−16 and has a triple eigenvalue; see how far the V⊤V of eig is from the identity: within the three-dimensional eigenspace it chooses vectors that need not be orthogonal. The second has eigenvalues 12 and −8, and eigh calmly returns 1 and 3, which belong to [2112].
For large sparse matrices, only a few eigenpairs are computed with Krylov methods. The Laplacian of a path with n nodes has known eigenvalues, 2−2cos(πk/n) for k=0,…,n−1, so it can check eigsh. For the smallest eigenvalues use shift-invert mode (sigma), which factorizes L−σI once and applies Lanczos to its inverse, where those eigenvalues become the largest.
How would you classify the quadratic form q(x)=x12+x22+x32+4x1x2+4x1x3+4x2x3 on R3?
NumericThe maximum on the circle
Find the maximum of 3x2+2xy+3y2 on the unit circle x2+y2=1.
NumericArea of a tilted ellipse
Find the area of the region 2x2+2xy+3y2≤1.
QuizPositive eigenvalues, indefinite form
Both eigenvalues of M=[1041] equal 1. What can you say about q(x)=x⊤Mx?
NumericA tilted vector, an almost exact eigenvalue
A is a symmetric 2×2 matrix with eigenvalues λ1=4 and λ2=2. You take a unit vector x at an angle of 0.1 radians to q1. What is the error λ1−R(x)?
NumericCount eigenvalues without computing them
For a symmetric matrix A∈R4×4, Gaussian elimination without exchanges applied to A−2I ends with pivots 3,−1,0.5,2. How many eigenvalues of A are greater than 2?
QuizInterlacing
A symmetric A∈R3×3 has eigenvalues 5,2,−1. Which pairs (μ1,μ2) can be eigenvalues of a 2×2 principal submatrix of such a matrix?
More than one answer may be correct.
NumericHow far can an eigenvalue rise?
A is symmetric with eigenvalues 5,3,1 and E is symmetric with all its eigenvalues in [−0.2,0.5]. What is the largest possible value of λ2(A+E)?
QuizWhich components are reliable?
An estimated covariance has eigenvalues 5.0, 4.8 and 1.0, and its error relative to the true covariance satisfies ∥E∥2≤0.05. Which claim is justified?
ProofWeyl's inequality
Prove: If A and E are symmetric, λk(A+E)≤λk(A)+λ1(E) for every k.
0
Order the eigenvalues from largest to smallest and use the Courant–Fischer max-min form: λk(M)=maxdimS=kminx∈S∖{0}RM(x).
Step 1 of 4. How are the Rayleigh quotients of A+E, A and 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=Qdiag(w)Q⊤, without modifying A. Stop when off(A)≤tol⋅∥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⊤, with real eigenvalues and orthogonal Q. The proof only needs q1⊥ to be invariant, and that is symmetry.
A quadratic form x⊤Ax is, in eigenvector axes, ∑iλiyi2: eigenvectors give the axes, 1/∣λ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, its minimum λn, its critical points are eigenvectors, and its eigenvalue estimate has error quadratic in vector error.
Courant–Fischer turns each λ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 moves them by at most ∥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.