Directions that a transformation only stretches reveal its structure. Define eigenvalues, eigenvectors, characteristic polynomials, multiplicities and defective matrices; interpret complex eigenvalues geometrically as rotations; and explain why practical algorithms do not compute them as polynomial roots.
After this lesson you can
Calculate eigenvalues and eigenvectors of 2×2 and 3×3 matrices, including complex ones.
Distinguish algebraic and geometric multiplicity and recognize defective matrices.
Interpret complex eigenvalues of real matrices as rotation and scaling in an invariant plane.
Prove that trace and determinant are the sum and product of eigenvalues.
Explain why computing eigenvalues as roots of the characteristic polynomial is numerically unstable.
A square matrix A∈Rn×n is a linear map from a space to itself. Generally it mixes coordinates: Ax points elsewhere and has another length. But often a few special directions exist in which A does not rotate, only stretches, shrinks or flips. Along those directions a map of n2 numbers behaves like multiplication by a scalar, a simplification that matters when repeatedly applying A or examining it closely.
Stability. A system evolving as xk+1=Axk (an autoregressive model, filter, or linearization around equilibrium) returns to rest, oscillates or explodes according to the magnitudes of its directional stretch factors. The same holds in continuous time for stability by linearization.
Stationary distributions. If P is a Markov-chain transition matrix, a distribution unchanged by one step satisfies Pπ=π: a direction left intact by P. PageRank is exactly this (studied as a stationary distribution).
Vibration modes. A mass-spring system obeys x¨=−Kx. For motions in which all masses oscillate together at one frequency, x(t)=vcos(ωt), the equation reduces to Kv=ω2v. Each mode is a direction of K and its frequency follows from the stretch factor.
Exploding gradients. In a linear recurrent network ht=Wht−1, the gradient with respect to h0 after t steps contains factor (W⊤)t. If any stretch factor of W exceeds 1 in magnitude, the gradient grows exponentially; if all are below 1, it vanishes. This underlies spectral conditions for RNN gradients.
Curvature. Eigendirections of a loss Hessian give maximum and minimum curvature directions, and their ratio determines gradient-descent convergence speed (see their spectrum in real networks).
This lesson builds the concept from geometry: what the directions and factors are, how to calculate them by hand, what happens when real ones do not exist (complex eigenvalues describe rotations), when there are too few (defective matrices), their relationship to trace and determinant, and why serious software does not compute them as polynomial roots. The next lesson, diagonalization and linear dynamics, uses them to understand Ak and etA.
Intuition: x and Ax on the same line
Take A=[1.50.512] and move vector x around the unit circle. For almost every x, image Ax leaves the line of x. But two directions do not: A(1,1)=(2.5,2.5) and A(2,−1)=(2,−1). The first stretches by 2.5 and the second remains fixed. These two lines tell us everything about A: every vector combines (1,1) and (2,−1), and A multiplies the first component by 2.5 while leaving the second.
InteractiveHunting eigenvectors
x on the unit circle
Ax and its ellipse
recorded eigenline
det[xAx] by angle of the line of x: zero at eigendirections
Entries of A
Angle of x20.1°
Angle from x to Ax13.4°
det[xAx]0.485
Directions visited0 %
Recorded eigenvaluesnone
Drag the tip of x around the circle, or press ‘Sweep’ to traverse it. The dashed ellipse is the image of the circle under A. When Ax lies on the line of x, the line lights up and factor λ is recorded. Below, signed area det[xAx] versus the angle of x: it vanishes exactly in eigendirections. Try reflection (what if Ax points opposite?), rotation (does the curve reach zero?) and shear (does it cross or merely touch?).
The lower graph turns the search into a root problem. The signed area of the parallelogram of x and Ax (the determinant from lesson 6) is zero exactly when vectors are parallel. With x=(cosθ,sinθ) and A=[acbd] compute it in one line:
det[xAx]=ccos2θ+(d−a)cosθsinθ−bsin2θ.
If cosθ=0, divide by cos2θ and write t=tanθ: eigendirections solve bt2+(a−d)t−c=0, with discriminant (a−d)2+4bc=(a+d)2−4(ad−bc), the squared trace minus four times the determinant. This decides whether there are two invariant lines, one or none (except A=cI, which leaves all invariant), and will reappear.
Three things the figure shows and the lesson formalizes:
The factor may be negative. Under reflection, Ax lies on the line of x but points opposite: factor −1. The line matters, not the sense.
There may be no real direction. A rotation by 60° turns every vector equally and the curve never touches zero. The factors exist, but are complex numbers.
There may be fewer directions than expected. Shear [1011] fixes only the horizontal line. The curve touches zero without crossing: a double root with only one direction.
Definition and characteristic polynomial
Two details matter. The zero vector is excluded because A0=λ0 for any λ would say nothing. An eigenvector is never unique: if v is one, so is cv for any c=0. What A determines is the line (or subspace), not the vector. We work in C from the start because, as rotation showed, a real matrix need not have any real eigendirection.
How do we find them? Rewrite the equation as (A−λI)v=0. Seek a nonzero vector in the null space of A−λI; for a square matrix that means singularity:
λ∈σ(A)⟺null(A−λI)={0}⟺det(A−λI)=0.
The last condition no longer mentions v: it is an equation only in λ.
Why degree n? By Leibniz’s formula, det(A−λI) is a sum of products of n entries of A−λI, one per row and column. Each entry is a number or a number minus λ, so each product has degree at most n. Only the diagonal product reaches degree n, namely ∏i(aii−λ), contributing (−1)nλn. Expanding further gives the general form:
pA(λ)=(−1)nλn+(−1)n−1(trA)λn−1+⋯+detA.
The constant term is pA(0)=detA. We justify the coefficient of λn−1 below. Some books and np.poly use det(λI−A)=(−1)npA(λ), which is monic. It has the same roots; only the overall sign changes when n is odd.
By the fundamental theorem of algebra, pA factors over C as
pA(λ)=(λ1−λ)(λ2−λ)⋯(λn−λ),
so every matrix n×n has exactly n complex eigenvalues counting multiplicity, and at least one. This is the underlying reason for working in C: over R even one is not guaranteed.
Two complete examples
The 2×2 closed formula
For A=[acbd], with trace τ=a+d and determinant δ=ad−bc,
pA(λ)=λ2−τλ+δ,λ1,2=2τ±τ2−4δ.
Discriminant Δ=τ2−4δ is the same one found when searching for directions using tanθ. If Δ>0 there are two distinct real eigenvalues; if Δ=0, one double; if Δ<0, a complex conjugate pair τ/2±i−Δ/2. No system is needed for an eigenvector: if (b,λ−a)=0, it is an eigenvector because it annihilates the first row of A−λI by construction, and the second row is proportional when λ is an eigenvalue. If this gives zero, (λ−d,c) works with the second row.
Eigenspaces and multiplicities
If v and w are eigenvectors for the same λ, any combination αv+βw is too (or is zero). An eigenvalue’s eigenvectors together with 0 form a subspace.
The multiplicities measure different things: algebraic counts polynomial roots, geometric counts directions. The three examples in the hunt figure distinguish them:
Matrix
Eigenvalues
m
g
[2112]
3,1
1,1
1,1
1.5I
1.5
2
2
[1011]
1
2
1
Scaling 1.5I stretches every direction equally: E1.5=R2. The shear has the same characteristic polynomial as identity, (1−λ)2, but A−I=[0010] has rank 1 and its null space is only the line of e1.
Proof
The lower bound is the definition: if λ0 is an eigenvalue, at least one eigenvector exists. For the upper bound let g=g(λ0) and let v1,…,vg be a basis of Eλ0. Extend it to a basis v1,…,vn of Cn and write P=[v1⋯vn], which is invertible. Since Avj=λ0vj for j≤g, the first g columns of P−1AP are λ0ej, giving block form
P−1AP=[λ0Ig0BD].
Similar matrices share the characteristic polynomial, since det(P−1AP−λI)=det(P−1(A−λI)P)=det(A−λI). A block triangular determinant is the product of diagonal-block determinants. Thus pA(λ)=(λ0−λ)gdet(D−λI), and λ0 is a root of multiplicity at least g.
∎
Eigenvectors of distinct eigenvalues are independent
The proof is short and instructive: take the first dependence and apply A. You will work it step by step in the guided exercise. Two immediate consequences:
If A has n distinct eigenvalues, it has an eigenvector basis. Combining bases of distinct eigenspaces also gives an independent set (the same argument works for subspaces), so an eigenvector basis exists if and only if g(λ)=m(λ) for every eigenvalue. This is the diagonalizability condition of the next lesson.
The sum of eigenspace dimensions is at most n, with equality exactly in the preceding case.
Defective matrices
A matrix is defective if an eigenvalue has g(λ)<m(λ): it lacks enough eigendirections for a basis. The shear is the smallest example. Its sole eigenvalue is the double 1 and its only eigendirection is horizontal: other vectors slide right without returning to their own lines.
Defective matrices are rare in a precise sense: arbitrarily small perturbations can make them diagonalizable by splitting the double root (though not every perturbation does: [101+ε1] remains defective). But this makes them dangerous in floating point. With Aε=[1ε11], the polynomial is (1−λ)2−ε and eigenvalues are 1±ε. A perturbation of size 10−12 in one entry moves eigenvalues by 10−6: a million times more. Generally a defective block of size m turns perturbations of size ε into changes of size ε1/m (quantified by Jordan form; numerical analysis is eigenvalue sensitivity).
Complex eigenvalues: rotation and scaling
Rotation by angle θ, Rθ=[cosθsinθ−sinθcosθ], has trace 2cosθ and determinant 1, so p(λ)=λ2−2cosθλ+1 and
λ=cosθ±isinθ=e±iθ,
by Euler’s formula. An eigenvector of eiθ is (1,−i): check by multiplication. In C2 rotation does have eigendirections, just not real ones. Eigenvalue magnitude is 1 (no stretching) and its argument is the rotation angle. This interpretation generalizes.
What does a real matrix with a complex pair do geometrically? The next theorem says it rotates and scales in a suitable real plane.
Proof
Separate real and imaginary parts in A(u+iw)=(a−bi)(u+iw)=(au+bw)+i(aw−bu). Since A is real,
Au=au+bw,Aw=−bu+aw,
which in matrix form is A[uw]=[uw]C. It remains to show P invertible. If u and w were dependent, there would be real vector z=0 and complex γ=0 with v=γz (if w=su, take z=u and γ=1+is; if u=0, z=w and γ=i). Then Az=λz, with Az real and λz having imaginary part −bz=0. Contradiction.
∎
Choose λ=a−bi with b>0, the member with negative imaginary part, so φ∈(0,π) and rotation is counterclockwise; the other member gives C⊤, opposite rotation, and the conjugate eigenvector. Since A=PCP−1, the power is Ak=PCkP−1 with Ck=rkRkφ: iterates Akx0 rotate φ per step and their size is multiplied by r. In standard coordinates the circle becomes an ellipse.
InteractiveRotation and scaling in an invariant plane
iterates xk=Akx0
u=Rev
w=Imv
orbit of x0 if ∣λ∣=1
Entries of A
Coordinates
k = 16
λ=0.75±0.73i
∣λ∣ (scale per step)1.049
φ=argλ (rotation per step)44.3°
C=[0.750.73−0.730.75]
Matrix of A in the (u, w) basis
∥xk∥2.180
Points are iterates xk=Akx0 and the faint curve the continuous spiral joining them. Play them, then change coordinates to basis (u,w) from real and imaginary parts of the eigenvector: the elliptical spiral becomes circular and each step rotates exactly φ. Compare examples: ∣λ∣>1 outward, ∣λ∣<1 inward, ∣λ∣=1 (that is, detA=1) a closed orbit on the dashed ellipse. Edit A until eigenvalues become real: what disappears?
For A=[11−11], τ=2 and δ=2, so λ=1±i, ∣λ∣=2 and φ=45°. This is 2R45°: each application rotates by 45° and multiplies lengths by 2. In higher dimensions the story repeats across planes. A real 3×3 matrix has an odd-degree characteristic polynomial, so at least one real eigenvalue. If the other two are complex, the real eigenvector is an invariant axis and the plane of u,w is a plane where A rotates and scales. A rotation of R3 has eigenvalues 1,eiθ,e−iθ: 1 gives the axis and θ the angle. Generally every real matrix is orthogonally similar to an upper quasi-triangular matrix with diagonal blocks 1×1 (real eigenvalues) and 2×2 (complex pairs): real Schur form, which actual algorithms compute.
The complete 2×2 map
Combine these results for real 2×2. Eigenvalues depend only on τ and δ, and plane (τ,δ) is divided by parabola δ=τ2/4:
Below the parabola (Δ>0): two distinct real eigenvalues and two invariant lines. If also δ<0, signs differ: one direction stretches and the other flips.
On the parabola (Δ=0): double eigenvalue τ/2. Either A=2τI or A is defective.
Above (Δ<0, requiring δ>0): a complex pair with real part τ/2 and magnitude δ. No real line is invariant and A rotates.
InteractiveArrow field and invariant lines
arrow at x in direction Ax
eigenspace of λ1
eigenspace of λ2
Trace (τ, horizontal) and determinant (δ, vertical) plane: the point is A. On the parabola τ2=4δ the eigenvalues coincide.
Entries of A
A=[1.000.501.001.00]
Trace τ2.00
Determinant δ0.50
Discriminant τ2−4δ2.000
λ1=1.71,λ2=0.29
Positive discriminant: two invariant lines with radial arrows.
At each point x an arrow points in direction Ax. On colored eigenspaces arrows are radial: outward if λ>0, inward if λ<0. Along the guided path A=[1c11], with eigenvalues 1±c, slowly decrease c: the lines close like scissors, merge at c=0 (the shear), and disappear when c<0 as point (τ,δ) crosses the parabola. Try the saddle too: which way do arrows point on each line?
On the guided path, τ=2 and δ=1−c: the point moves vertically along line τ=2 and crosses the parabola exactly at δ=1. On one side 1±c are real; on the other 1±i−c. This collision of two real roots leaving the axis as a conjugate pair is the only way a real matrix can lose real eigenvalues under continuous deformation.
Trace, determinant and similarity
Return to factorization pA(λ)=∏i(λi−λ) and compare it with the polynomial’s general form. Two coefficients are immediate.
This relates trace, determinant and eigenvalues. The determinant part is immediate: evaluate both polynomial expressions at λ=0, giving detA=pA(0)=∏iλi. Trace follows by comparing coefficients of λn−1, reconstructed in a guided exercise. First, three frequently used consequences:
A is invertible if and only if 0 is not an eigenvalue, because detA=∏iλi.
For a 2×2, τ and δ suffice. If one eigenvalue is known, the other is τ−λ1, and if both are real and δ<0 they have opposite signs.
A real matrix has real sum and product even with complex eigenvalues, because each conjugate pair contributes (a+bi)+(a−bi)=2a to the sum and (a+bi)(a−bi)=a2+b2 to the product.
InteractiveRoots of the characteristic polynomial
p(λ)=det(A−λI) on the real line
Roots in the complex plane
eigenvalue (root of p); hollow on the left: real part of a complex pair
trail as A changes
cross: center trA/n
Size
Matrix A
p(λ)=λ2−3λ+1
λ12.618
λ20.382
∑iλi3.000
trA3.000
∏iλi1.000
detA1.000
On the left, p(λ)=det(A−λI) on the real line: axis crossings are real eigenvalues. On the right, all roots in the complex plane, with trails as A changes. Lower a21: two real roots approach, collide and leave the axis as a conjugate pair symmetric about it, while the left graph stops crossing. The cross is trA/n, the roots' center of mass, unchanged by off-diagonal entries. Readouts compare ∑λi with trace and ∏λi with determinant. Switch to 3×3: a real cubic always crosses at least once.
Similar matrices B=P−1AP represent the same linear map in another basis (change of basis). They share the characteristic polynomial and thus eigenvalues with algebraic multiplicities, and hence trace and determinant. Eigenvectors change as the same vectors expressed in the new basis: if Av=λv, then B(P−1v)=P−1Av=λP−1v. Eigenvalues belong to the map, not the representing matrix.
Eigenvalues for free
Many matrices built from A have eigenvalues deducible directly from those of A. Check each statement by applying the matrix to an eigenvector.
Proof
(1) T−λI is triangular and its determinant is the diagonal product, ∏i(tii−λ). (2) By induction Ak+1v=A(λkv)=λk+1v; for polynomials sum term by term. (3) λ=0 would give Av=0 with v=0; applying A−1 to Av=λv gives v=λA−1v. (4) The first equality is direct, the second applies (3) to A−σI, whose eigenvalue λ−σ is nonzero. (5) det(A⊤−λI)=det((A−λI)⊤)=det(A−λI).
∎
Each item is a tool. Item (1) says triangularizing Aby similarity solves the problem: exactly what the QR algorithm does (Gaussian elimination triangularizes too, but not by similarity, and changes eigenvalues). Item (2) underlies the next lesson’s linear dynamics: eigenvalues of Ak are λik, tending to zero if ∣λi∣<1 and exploding if ∣λi∣>1. Item (4) gives shift-and-invert: (A−σI)−1 has dominant eigenvalue 1/(λ−σ) for λ closest to σ, isolating any spectral eigenvalue (used in inverse iteration). Eigenvectors of A⊤ satisfying y⊤A=λy⊤ are left eigenvectors; in Markov chains the two types have different meanings.
In fact eigenvalues of q(A) are exactly q(λ1),…,q(λn) counting multiplicity, although the preceding argument gives only one inclusion; triangular form shows this next lesson.
Applying A repeatedly
Suppose A has eigenvector basis v1,…,vn with ∣λ1∣>∣λ2∣≥⋯≥∣λn∣. Write an initial vector in that basis, x0=c1v1+⋯+cnvn. By item (2) above,
Every ratio λi/λ1 with i≥2 has magnitude below 1. If c1=0, the direction of Akx0 converges to v1, and error (e.g. sine of the angle with the line of v1) decays as ∣λ2/λ1∣k. Normalizing at each step preserves direction and avoids overflow: this is power iteration, used to compute the PageRank vector.
InteractiveApplying A repeatedly
measured sin ∠(xₖ, v₁)
prediction |c₂/c₁| sin∠(v₁,v₂) |r|ᵏ
line of v1, λ1=1
line of v2, λ2=0.80
iterates xk
k = 40
A=[0.970.050.090.83]
Iteration k40
Angle from xk to the line of v10.04°
∣λ2/λ1∣k1.3e−4
∥Axk∥ (tends to ∣λ1∣=1)1.0000
Steps for error 10−6≈ 62
A has fixed nonorthogonal eigenvectors v1 and v2, with λ1=1 and adjustable λ2. Each iterate is xk+1=Axk/∥Axk∥. Play and watch iterates approach the line of v1. On the graph, log-scale error follows a line of slope log∣λ2/λ1∣ matching prediction. Set the ratio to 0.98 and 0.2; then negative, where iterates alternate sides; finally ±1. Drag x0 onto the line of v2: what happens?
Speed depends on the gap between dominant eigenvalues, not the size of A. With ∣λ2/λ1∣=0.9, reducing error by factor 106 takes about 132 iterations; with 0.5 only 20. Case ∣λ2∣=∣λ1∣ does not converge: with λ2=−λ1 iterates oscillate between two directions, and with a dominant complex pair they rotate indefinitely, as in the earlier spiral.
Stationary distributions
A matrix P∈Rn×n is column stochastic if entries are nonnegative and each column sums to 1: pij is the probability of moving from state j to i, and if x is a probability distribution over states, Px is the distribution one step later. Two facts connect it to this lesson:
1 is an eigenvalue. Columns summing to 1 means 1⊤P=1⊤, i.e. P⊤1=1. Thus 1 is an eigenvalue of P⊤ and, by item (5), P. An eigenvector with nonnegative entries summing to 1 is a stationary distribution, Pπ=π.
No eigenvalue has magnitude above 1. If P⊤y=λy and ∣yi∣ is the largest component in magnitude, ∣λ∣∣yi∣=∑jpjiyj≤∑jpji∣yi∣=∣yi∣, because column i of P sums to 1.
If eigenvalue 1 is simple and all others have strictly smaller magnitude (for instance, if all entries of P are positive, by Perron–Frobenius), iterating xk+1=Pxk from any distribution converges to π with error O(∣λ2∣k) (times a polynomial in k if P is not diagonalizable). This is power iteration without normalization, since P preserves the sum. Implement it below.
Implementation from scratch
First, the numerically stable closed formula for 2×2, checking eigenpairs and their relation to trace and determinant.
[ ]2×2 eigenvalues by handBrowser
import numpy as np
def eigvals2x2(A):
"""Autovalores de una 2x2 real por la fórmula cerrada, sin cancelación."""
(a, b), (c, d) = np.asarray(A, dtype=float)
tau, delta = a + d, a * d - b * c
disc = tau * tau - 4 * delta
if disc < 0: # par conjugado
s = np.sqrt(-disc) / 2
return complex(tau / 2, s), complex(tau / 2, -s)
q = (tau + np.copysign(np.sqrt(disc), tau)) / 2 # la raíz de mayor módulo, sin restar
if q == 0: # tau = disc = 0: los dos son nulos
return 0.0, 0.0
return float(q), float(delta / q) # la otra, de lambda1 * lambda2 = delta
def eigvec2x2(A, lam):
"""Vector unitario del núcleo de A - lam I: perpendicular a su fila de mayor norma."""
B = np.asarray(A, dtype=complex) - lam * np.eye(2)
fila = B[0] if np.linalg.norm(B[0]) >= np.linalg.norm(B[1]) else B[1]
if np.linalg.norm(fila) == 0: # A = lam I: cualquier vector sirve
return np.array([1.0, 0.0])
v = np.array([-fila[1], fila[0]])
v = v / np.linalg.norm(v)
return v.real if np.allclose(v.imag, 0) else v
ejemplos = {
"simétrica": [[2, 1], [1, 2]],
"no simétrica": [[1.5, 1], [0.5, 2]],
"cizalla": [[1, 1], [0, 1]],
"rotación 90°": [[0, -1], [1, 0]],
"rotación y escala": [[1, -1], [1, 1]],
}
for nombre, A in ejemplos.items():
A = np.array(A, dtype=float)
l1, l2 = eigvals2x2(A)
v1 = eigvec2x2(A, l1)
res = np.linalg.norm(A @ v1 - l1 * v1)
print(f"{nombre:18s} λ = {l1:.4g}, {l2:.4g} |Av - λv| = {res:.1e} "
f"|λ1 + λ2 - tr| = {abs(l1 + l2 - np.trace(A)):.0e} |λ1 λ2 - det| = {abs(l1 * l2 - np.linalg.det(A)):.0e}")
A = np.array([[1e8, 1.0], [0.0, 1e-8]])
tau, delta = np.trace(A), A[0, 0] * A[1, 1] - A[0, 1] * A[1, 0]
de_libro = (tau - np.sqrt(tau**2 - 4 * delta)) / 2
print("\nautovalor pequeño de diag(1e8, 1e-8) + cizalla:")
print(" fórmula de libro:", de_libro, " forma estable:", eigvals2x2(A)[1], " exacto: 1e-08")
Notice eigvec2x2: instead of always using the first row, which may be zero or nearly zero, it takes the largest-norm row. This is the pivoting principle in Gaussian elimination. For the shear it returns (1,0), the only eigenvector, and nothing warns another is missing; the final code exercise asks you to detect this.
Now the stationary distribution of a small five-page network, PageRank-style. The link matrix is column-normalized and mixed with a uniform jump of probability 1−α, making every entry positive.
[ ]Stationary distribution by iterationBrowser
import numpy as np
import matplotlib.pyplot as plt
# L[i, j] = 1 si la página j enlaza a la i
L = np.array([
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 0, 0, 1, 0],
], dtype=float)
S = L / L.sum(axis=0) # cada página reparte su probabilidad entre sus enlaces
alfa, n = 0.85, L.shape[0]
P = alfa * S + (1 - alfa) / n # estocástica por columnas, todas las entradas > 0
def estacionaria(P, x0, tol=1e-13, max_iter=2000):
x = np.array(x0, dtype=float)
errores = []
for _ in range(max_iter):
x_nuevo = P @ x
errores.append(np.abs(x_nuevo - x).sum())
x = x_nuevo
if errores[-1] < tol:
break
return x, np.array(errores)
x0 = np.eye(n)[0] # toda la probabilidad empieza en la página 1
pi, errores = estacionaria(P, x0)
print("iteraciones:", len(errores), " pi =", np.round(pi, 4), " suma =", round(pi.sum(), 12))
# comparación con los autovalores
w = np.linalg.eigvals(P)
w = w[np.argsort(-np.abs(w))]
print("autovalores de P:", np.round(w, 4))
print("módulos: ", np.round(np.abs(w), 4))
k = np.arange(len(errores))
tasa = np.exp(np.polyfit(k[10:60], np.log(errores[10:60]), 1)[0])
print(f"tasa de convergencia medida: {tasa:.3f} |λ2| = {abs(w[1]):.3f}")
# desde la distribución uniforme
_, errores_u = estacionaria(P, np.full(n, 1 / n))
ku = np.arange(len(errores_u))
tasa_u = np.exp(np.polyfit(ku[5:30], np.log(errores_u[5:30]), 1)[0])
print(f"desde la uniforme: {len(errores_u)} iteraciones, tasa medida {tasa_u:.3f}")
plt.semilogy(k, errores, label="desde la página 1")
plt.semilogy(ku, errores_u, label="desde la uniforme")
plt.semilogy(k, errores[10] * np.abs(w[1]) ** (k - 10), "--", color="gray", label="pendiente |λ₂|^k")
plt.xlabel("iteración k"); plt.ylabel("‖x_{k+1} − x_k‖₁"); plt.legend(); plt.show()
Starting at page 1, measured rate matches ∣λ2∣=0.688 to three digits. From a uniform distribution it converges much faster, at rate 0.425: this graph is unchanged by simultaneously swapping pages 1 and 5 and pages 3 and 4; the λ2 mode is antisymmetric under that swap, and the symmetric uniform vector has no component along the eigenvector of λ2 (c2=0, as when dragging x0 onto the line of v2 above), so the next magnitude dominates, that of complex pair −0.2125±0.3681i. This pair also shows a real stochastic matrix may have complex eigenvalues. Notice ∣λ2∣=0.6877≤α. This is no accident: for the Google matrix ∣λ2∣≤α always, a result of Haveliwala and Kamvar (2003). Thus damping factor α directly controls iteration count.
Why they are not computed as polynomial roots
The definition suggests calculating coefficients of pA and finding roots. This is a bad idea: polynomial roots can be extraordinarily sensitive to coefficients even when the original matrix’s eigenvalues are not. J. H. Wilkinson’s classic late-1950s example is w(x)=(x−1)(x−2)⋯(x−20), whose roots are eigenvalues of diag(1,2,…,20), the best-conditioned matrix imaginable.
[ ]Wilkinson's polynomialBrowser
import numpy as np
lam = np.arange(1.0, 21.0)
coef = np.poly(lam) # coeficientes de (x-1)(x-2)...(x-20)
print("algunos coeficientes:", coef[:4], "...", coef[-1])
r_pol = np.roots(coef)
r_pol = r_pol[np.argsort(r_pol.real)]
r_eig = np.sort(np.linalg.eigvals(np.diag(lam)).real)
print("error máximo, raíces del polinomio:", np.max(np.abs(r_pol - lam)))
print("error máximo, eigvals de la matriz:", np.max(np.abs(r_eig - lam)))
# Wilkinson: cambiar el coeficiente de x^19 (que es -210) en 2^-23
coef2 = coef.copy()
coef2[1] -= 2.0**-23
r2 = np.roots(coef2)
print("\nraíces tras perturbar un coeficiente en 1.2e-7:")
print(np.round(r2[np.argsort(r2.real)], 3))
Coefficients are integers reaching 1.4×1019 (the constant term is 20!≈2.4×1018), far above integers float64 represents exactly (253≈9×1015), so storage alone introduces relative error 10−16. Roots computed from them deviate by order 10−1. Changing the coefficient of x19 from −210 to −210−2−23, a relative perturbation 6×10−10, turns ten roots into five complex pairs with imaginary parts up to 2.8. Wilkinson later described it in an aptly titled essay, “The perfidious polynomial” (1984).
Passing from matrix to coefficients destroys information: “eigenvalues of diag(1,…,20)” is perfectly conditioned, whereas “roots of w” is not. For diagonalizable matrices, Bauer–Fike quantifies intrinsic sensitivity: every eigenvalue of A+E lies within κ(V)∥E∥2 of some eigenvalue of A=VΛV−1, where κ(V) is the eigenvector matrix’s condition number. If eigenvectors are orthogonal (symmetric matrices), κ=1 and eigenvalues are as stable as possible. If nearly parallel, as near a defective matrix, sensitivity soars.
[ ]The defective matrix up closeBrowser
import numpy as np
for eps in [1e-4, 1e-8, 1e-12]:
w = np.linalg.eigvals(np.array([[1.0, 1.0], [eps, 1.0]]))
print(f"eps = {eps:.0e}: |λ - 1| = {np.max(np.abs(w - 1)):.1e} sqrt(eps) = {np.sqrt(eps):.1e}")
w, V = np.linalg.eig(np.array([[1.0, 1.0], [0.0, 1.0]]))
print("\neig de la cizalla:", w)
print(V)
print("número de condición de V:", np.linalg.cond(V))
NumPy returns two “eigenvectors” for the shear that agree except for sign and a component of size 10−16: matrix V is numerically singular. This is not an error: no eigenvector basis exists, and eig can signal it only through ill-conditioned V.
What do libraries do instead? np.linalg.eig calls LAPACK routine geev, which does three things. First reduce A to Hessenberg form (zeros below the first subdiagonal) using Householder reflections in O(n3). Then apply Francis’s shifted QR algorithm, generating a sequence of similar matrices via orthogonal transformations converging to real Schur form: quasi-triangular, with eigenvalues in diagonal blocks 1×1 and 2×2. Finally obtain eigenvectors of that triangular form and transform them back. All uses orthogonal transformations without forming the characteristic polynomial. According to Golub and Van Loan, this costs about 10n3 operations for eigenvalues alone and 25n3 if Schur vectors are also wanted. QR, shifts and variants for symmetric and sparse matrices (Lanczos, Arnoldi) are covered in the QR algorithm.
The professional version
Function
Returns
When to use
np.linalg.eigvals(A)
eigenvalues
only eigenvalues needed (cheaper)
np.linalg.eig(A)
w, V with A @ V[:, i] = w[i] * V[:, i]
general square matrix
np.linalg.eigh(A)
sorted real eigenvalues, orthonormal eigenvectors
symmetric or Hermitian (lesson 12)
scipy.linalg.eig(A, left=True)
also left eigenvectors
Markov chains, sensitivity
scipy.sparse.linalg.eigs(A, k)
k extreme eigenvalues
large sparse matrices (Arnoldi)
torch.linalg.eig(A)
always complex tensors
inside a PyTorch model
[ ]np.linalg.eig versus what we knowBrowser
import numpy as np
A = np.array([[4.0, 1.0], [2.0, 3.0]])
w, V = np.linalg.eig(A)
print("autovalores:", w) # no vienen ordenados
print("autovectores (en COLUMNAS):\n", V)
print("normas de las columnas:", np.linalg.norm(V, axis=0))
print("A V = V diag(w):", np.allclose(A @ V, V * w))
# comparar con eigvals2x2, definida más arriba: mismos valores, quizá en otro orden
print("desde cero:", eigvals2x2(A))
# autovalores complejos: la salida pasa a dtype complejo
B = np.array([[1.0, -1.0], [1.0, 1.0]])
wB, VB = np.linalg.eig(B)
print("\n", wB, " módulos:", np.abs(wB), " ángulos:", np.degrees(np.angle(wB)))
j = np.argmin(wB.imag) # el autovalor a - bi con b > 0, aquí 1 - i
u, wim = VB[:, j].real, VB[:, j].imag
P = np.column_stack([u, wim])
print("P^-1 B P =\n", np.round(np.linalg.solve(P, B @ P), 12))
# una rotación de R^3 alrededor del eje (1, 1, 1): eje = autovector real de 1
a = np.ones(3) / np.sqrt(3)
K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
th = np.pi / 3
R = np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K
wR, VR = np.linalg.eig(R)
i = np.argmin(np.abs(wR - 1))
print("\nautovalores de la rotación:", np.round(wR, 4), " ángulos:", np.round(np.degrees(np.angle(wR)), 2))
print("eje:", np.round(VR[:, i].real / VR[0, i].real, 6))
The correspondence is direct: eigvals2x2 gives the same numbers in a different order, the real form of a complex pair comes from real and imaginary parts of a column of V, and rotation of R3 shows its axis as eigenvector of λ=1 and its angle as argument of the complex pair. PyTorch has the same interface:
import torchA = torch.tensor([[4.0, 1.0], [2.0, 3.0]])w, V = torch.linalg.eig(A) # w y V son complex64 aunque los autovalores sean realesw_real = torch.linalg.eigvals(A).realL, Q = torch.linalg.eigh(A @ A.T) # simétrica: autovalores reales y ascendentes
Two PyTorch documentation warnings matter in training: eigenvectors returned by eig are defined only up to a unit-magnitude complex factor, so loss must not depend on that phase; and eigenvector gradients are unstable (or undefined) when eigenvalues repeat or are close, because they contain terms 1/(λi−λj).
Common mistakes
Exercises
NumericThe largest eigenvalue
Calculate the largest eigenvalue of A=[2112].
NumericMagnitude of a complex pair
Calculate the magnitude ∣λ∣ of eigenvalues of A=[11−11].
QuizThe shear's multiplicities
For shear [1011], what are algebraic and geometric multiplicities of its sole eigenvalue λ=1?
QuizWhat do the iterates do?
Let A=[34−2−1] and xk=Akx0 with x0=0. What do the iterates describe?
QuizWhat is preserved?
Which statements hold for all A,B∈Rn×n?
More than one answer may be correct.
NumericDeterminant from trace
A real matrix A∈R3×3 has eigenvalue 1+2i and trace 4. What is detA?
NumericShift and invert
A has eigenvalues 1, 3 and 7. What is the eigenvalue of greatest magnitude of (A−2.5I)−1?
NumericHow many iterations?
In power iteration error decays as ∣λ2/λ1∣k. If ∣λ2/λ1∣=0.9, what is the smallest k with 0.9k≤10−6?
NumericA chain's second eigenvalue
A two-state Markov chain has column-stochastic transition matrix P=[0.90.10.20.8]. Without solving a polynomial, what is its second eigenvalue?
Prove: If v1,…,vk are eigenvectors of A with pairwise distinct eigenvalues λ1,…,λk, they are linearly independent.
0
Suppose for contradiction they are linearly dependent.
Step 1 of 4. Where do you begin?
ProofTrace and determinant from the polynomial
Prove: If λ1,…,λn are eigenvalues of A∈Cn×n counted with multiplicity, then detA=∏iλi and trA=∑iλi.
0
By the fundamental theorem of algebra, pA(λ)=det(A−λI)=(λ1−λ)(λ2−λ)⋯(λn−λ).
Step 1 of 4. How do you obtain detA?
CodeEigenvalues and eigenvectors of a 2×2 matrix
Implement eig2x2(A), returning (w, V): an array w of shape (2,) with eigenvalues and a 2×2 matrix V whose columns are unit eigenvectors, satisfying A @ V[:, j] = w[j] * V[:, j]. Order real values descending; for complex values put the positive imaginary part first. Special cases: for a double eigenvalue with A=λI, return V = I; for a defective double eigenvalue repeat the sole eigenvector in both columns. Use the stable no-cancellation form for real eigenvalues and do not call np.linalg.eig or eigvals.
import numpy as np
def eig2x2(A):
"""Devuelve (w, V): autovalores w (forma (2,)) y autovectores unitarios en las columnas de V."""
A = np.asarray(A, dtype=float)
(a, b), (c, d) = A
tau, delta = a + d, a * d - b * c
# tu código: discriminante; casos real, doble (escalar o defectivo) y complejo;
# y un vector del núcleo de A - lambda I para cada autovalor
w = np.zeros(2)
V = np.eye(2)
return w, V
Shift+Enter to run
Summary
Key idea
An eigenvector is a direction A does not rotate, only scales by its eigenvalue λ; along those directions a matrix behaves like a number, so eigenvalues govern what happens when repeatedly applying A.
Eigenvalues are roots of pA(λ)=det(A−λI), and each eigenspace is Eλ=null(A−λI). In C there are always n eigenvalues counting multiplicity.
Geometric multiplicity (directions) lies between 1 and algebraic multiplicity (roots). If smaller, the matrix is defective like the shear and lacks an eigenvector basis; its eigenvalues are highly perturbation-sensitive.
A real matrix with complex pair a∓bi rotates and scales: in basis (Rev,Imv) it is ∣λ∣ times rotation by angle argλ.
trA=∑λi and detA=∏λi are similarity invariants. Powers, inverses and shifts transform eigenvalues as numbers: λk, 1/λ, λ−σ.
Iterating A aligns a vector with the dominant eigenvector at rate ∣λ2/λ1∣k: power iteration and a way to compute stationary distributions.
In practice characteristic-polynomial roots are not computed: use eig (Hessenberg plus shifted QR), operating on the matrix via orthogonal transformations.