# eigenvectors

> the directions a matrix only stretches, and by how much.

source: https://learning.anthnydas.com/math/eigenvectors/

## tl;dr

a matrix moves every vector, and most of them change direction. an eigenvector doesn't. the matrix only stretches it, and the stretch is its eigenvalue. find the eigenvalues from det(A − λI) = 0, the directions from (A − λI)v = 0, and apply the matrix again and again to see the biggest one take over.

- **the equation:** Av = λv (A only stretches v, by λ. v is not the zero vector)
- **finding λ:** det(A − λI) = 0 (for a 2×2, λ² − (trace)λ + det = 0)
- **finding v:** (A − λI)v = 0 (one row of the equation is enough)
- **trace and det:** λ₁ + λ₂ and λ₁λ₂ (the sum and the product of the eigenvalues)
- **powers:** Aⁿv = λⁿv (the biggest |λ| takes over. that's power iteration)
- **a rotation:** no real eigenvectors (every line turns off itself, unless it's a half turn)
- **a shear:** one direction (λ repeated, and one line keeps its direction)
- **reach for it:** the long-run shares of a random walk, where each step is a matrix, the axes a symmetric matrix stretches along, and by how much, how fast a repeated step settles, by |λ₂/λ₁| a step, Aⁿ without n multiplications, through A = PDP⁻¹

## the idea

a matrix is a rule that moves every vector, as the [matrices page](/math/matrices/) shows. take

$$
A = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}
$$

and feed it $v = (1, 0)$: out comes $Av = (2, 1)$, a vector pointing somewhere else. feed it $(0, 1)$ and get $(1, 2)$. most vectors change direction when $A$ acts on them. a few don't. $A(1, 1) = (3, 3)$, which is $3 \cdot (1, 1)$: the same direction, three times as long. and $A(1, -1) = (1, -1)$, untouched. those two are the eigenvectors of $A$, and the stretches, 3 and 1, are its eigenvalues. the movie sweeps a vector around the circle and watches for the moments when $v$ and $Av$ line up.

> **interactive figure:** an animation on a plane from −3.5 to 3.5 both ways: a unit vector v in cyan sweeps around the unit circle while Av in amber sweeps with it, for the matrix with rows (2, 1) and (1, 2). at 0°, v = (1, 0) and Av = (2, 1), turned 26.6°. at 45° the two line up, Av = 3v, and a dashed eigenline is drawn through the origin labeled λ = 3. between the lines Av turns by as much as 30°. at 135°, v = (−1, 1)/√2 and Av = v: a second eigenline, λ = 1. the rest of the turn finds nothing new, and Av's amber trail is an ellipse whose axes sit on the two eigenlines, reaching 3 from the center one way and 1 the other.

$v = (1, 0)$ in cyan, and $Av = (2, 1)$ in amber. the matrix turned it: $Av$ points $26.6°$ away from $v$. most vectors do this. the question is which ones don't.

sweep $v$ to $45°$, $v = (1, 1)/\sqrt{2}$. now $Av = (3, 3)/\sqrt{2} = 3v$: the same direction, three times as long. $v$ is an eigenvector, and its eigenvalue is 3. the dashed line is its eigenline: every vector on it is an eigenvector too, since $A(cv) = c\,Av = 3\,(cv)$.

on toward $135°$. between the two lines $Av$ turns away from $v$ again, by as much as $30°$. at $v = (-1, 1)/\sqrt{2}$ they meet: $Av = v$. a second eigenvector, with eigenvalue 1. this matrix leaves that direction alone.

the rest of the turn finds nothing new. at $225°$ and $315°$, $v$ is the negative of an eigenvector from before: the same line, the same $\lambda$. $Av$'s trail is an ellipse, and its axes are the two eigenlines: it reaches 3 from the center along $(1, 1)$ and 1 along $(1, -1)$. that is what this matrix does, said in one picture.

the definition in one line: $v$ is an eigenvector of $A$ when $Av = \lambda v$ for some number $\lambda$, with $v \ne 0$. the eigenvalue $\lambda$ says what happens along that line. $\lambda > 1$ stretches, $0 < \lambda < 1$ shrinks, $\lambda < 0$ flips the vector to the other side of the origin, and $\lambda = 0$ squashes it to the origin. the zero vector is left out because $A0 = \lambda 0$ holds for every $\lambda$, and a line needs a direction.

## explore

set the matrix with the sliders, or pick one of the four presets, and drag the tip of $v$. $Av$ follows in amber, and the dashed lines are the eigenlines with their $\lambda$. put $v$ on one and the angle between $v$ and $Av$ drops to $0°$, or reaches $180°$ where $\lambda$ is negative.

> **interactive figure:** an interactive plane from −4 to 4 both ways. buttons pick a preset matrix, diagonal, symmetric, shear or rotation, and four sliders set its entries a, b, c, d from −3 to 3 in steps of 0.5. a point drags the tip of v, in cyan, on a grid of halves inside ±2, or moves with the arrow keys; Av is drawn in amber, and the eigenlines dashed with their λ. a readout gives v, Av, the angle between them, the eigenvalues, the eigen-directions, and the trace and determinant. it opens on the symmetric matrix with rows (2, 1) and (1, 2) and v = (1, 0.5): Av = (2.5, 2), turned 12.1°, eigenvalues 3 and 1 along (1, 1) and (1, −1), trace 4 and det 3. the diagonal preset, rows (2, 0) and (0, 0.5), sends (1, 0.5) to (2, 0.25), turned 19.4°, with the axes as eigenlines. the shear, rows (1, 1) and (0, 1), sends it to (1.5, 0.5), turned 8.1°, with one eigenline along (1, 0) and λ = 1 twice. the rotation, rows (0, −1) and (1, 0), sends it to (−0.5, 1), turned 90°, and the readout says there are no real eigenvectors.

## try it

> **interactive figure:** a practice exercise with four kinds of question: whether a given vector is an eigenvector of a 2×2 matrix and with what λ, the eigenvalues of a small matrix, which direction power iteration ends up pointing along, and the trace or determinant from the eigenvalues. the matrix is shown as a grid, and once there is a pick an eigenvector question draws v and Av. it opens on whether (1, 1) is an eigenvector of the matrix with rows (2, 1) and (1, 2), which it is, with λ = 3, then on the eigenvalues of the matrix with rows (3, 1) and (0, 2), which are 3 and 2.

## the rules

### the definition

$$
Av = \lambda v, \qquad v \ne 0
$$

$A$ sends $v$ to a multiple of itself. the multiple is the eigenvalue. any nonzero multiple of $v$ is an eigenvector with the same $\lambda$, since $A(cv) = c\,Av = \lambda\,(cv)$, so an eigenvector is a direction, a line through the origin, more than one vector. the page writes one representative, like $(1, 1)$, and means the whole line.

### finding λ

$$
\begin{gathered}
\det(A - \lambda I) = 0 \\[6pt]
\lambda^2 - (a + d)\,\lambda + (ad - bc) = 0
\end{gathered}
$$

move everything in $Av = \lambda v$ to one side: $(A - \lambda I)v = 0$. that matrix sends a nonzero vector to zero, so it squashes a direction flat, so it has no inverse, so its determinant is 0. the key idea below walks through it. for a $2 \times 2$ with entries $a, b, c, d$, the determinant is $(a - \lambda)(d - \lambda) - bc$, which is the quadratic above: $\lambda^2$ minus the trace times $\lambda$ plus the determinant. its two roots are the eigenvalues, and the discriminant $(a + d)^2 - 4(ad - bc)$ decides how many are real: two when it's positive, one repeated when it's 0, none when it's negative.

### finding v

$$
(A - \lambda I)\,v = 0
$$

with $\lambda$ in hand, the directions come from the matrix $A - \lambda I$. its determinant is 0, so its two rows are multiples of each other, and either one that isn't all zeros is enough. the row $(p, q)$ asks for $px + qy = 0$, and $(q, -p)$ answers it. for the movie's matrix at $\lambda = 3$, $A - 3I$ has rows $(-1, 1)$ and $(1, -1)$: $-x + y = 0$, so $v = (1, 1)$.

### trace and determinant

$$
\begin{gathered}
\lambda_1 + \lambda_2 = a + d \\[4pt]
\lambda_1 \lambda_2 = ad - bc
\end{gathered}
$$

multiply out $(\lambda - \lambda_1)(\lambda - \lambda_2)$ and it's $\lambda^2 - (\lambda_1 + \lambda_2)\lambda + \lambda_1 \lambda_2$, the same quadratic, since it has the same roots. match the coefficients: the trace is the sum of the eigenvalues and the determinant is their product, and both are a check on a hand computation. the movie's matrix has trace 4 and determinant 3, and $3 + 1 = 4$, $3 \cdot 1 = 3$. the determinant as a product says something on its own: the matrix scales areas by $\lambda_1 \lambda_2$, which is what stretching by $\lambda_1$ one way and $\lambda_2$ the other does to a square.

### the four cases

a diagonal matrix stretches the axes, so the axes are its eigenlines and the diagonal entries are its eigenvalues. a symmetric matrix, one with $b = c$, has real eigenvalues always and perpendicular eigenlines: the discriminant is $(a - d)^2 + 4b^2$, which can't be negative, and the key idea below does the perpendicular part. a shear, $(x, y) \mapsto (x + y, y)$, slides every point sideways by its height, so the $x$ axis is the only line that stays put, and $\lambda = 1$ comes out twice with one direction to show for it. a rotation turns every direction off its line, so there are no real eigenvectors, unless it's a half turn, which sends every $v$ to $-v$: $\lambda = -1$ on every line.

> **interactive figure:** four small panels, each with the unit circle in gray, where the matrix sends it as a dotted amber curve, the eigenlines dashed, and each unit eigenvector in cyan with where the matrix sends it in amber. diagonal, rows (2, 0) and (0, 0.5): the circle becomes an ellipse reaching 2 along the x axis and 0.5 along y, eigenlines along the axes with λ = 2 and λ = 0.5. symmetric, rows (2, 1) and (1, 2): an ellipse tilted 45°, eigenlines along (1, 1) with λ = 3 and (1, −1) with λ = 1. shear, rows (1, 1) and (0, 1): a leaning ellipse, one eigenline along (1, 0) with λ = 1 repeated. rotation, rows (0, −1) and (1, 0): the circle maps onto itself, and there are no eigenlines.

### powers

$$
A^n v = \lambda^n v
$$

if $A$ stretches $v$ by $\lambda$, applying it $n$ times stretches it by $\lambda^n$. that makes eigenvectors the way to understand a matrix applied over and over. write any start $v$ as a mix of the two eigenvectors, $v = c_1 v_1 + c_2 v_2$, and then

$$
A^n v = c_1 \lambda_1^n v_1 + c_2 \lambda_2^n v_2
$$

each part grows or shrinks on its own. if $|\lambda_1| > |\lambda_2|$, the first part wins: the ratio of the second to the first is $(\lambda_2 / \lambda_1)^n$ times what it was, so it shrinks by $|\lambda_2 / \lambda_1|$ every step, and $A^n v$ turns toward $v_1$. that's power iteration: apply $A$, scale the result back to length 1 so the numbers stay in range, and repeat. the angle left between the vector and the eigenline shrinks by about $|\lambda_2 / \lambda_1|$ a step, and the rayleigh quotient $v \cdot Av / v \cdot v$ closes in on $\lambda_1$. a ratio near 0 settles in a few steps. a ratio near 1 takes many.

> **interactive figure:** an interactive unit circle from −1.5 to 1.5 both ways. buttons pick a matrix: λ = 3 and 1, rows (2, 1) and (1, 2); λ = 1.2 and 1, rows (1.1, 0.1) and (0.1, 1.1); λ = 1 and 0.4, the two-room walk with rows (0.9, 0.5) and (0.1, 0.5); and λ = 1 and −1, rows (1, 0) and (0, −1). a point drags the start vector v₀, in cyan, on a grid of tenths, or moves with the arrow keys; a slider or a step button applies the matrix up to 12 times, scaling to length 1 each time, and the vector after n steps is drawn in white with the earlier steps as gray dots on the circle. the eigenlines are dashed with their λ. a readout gives the vector, the rayleigh quotient, the angle to the dominant eigenline, that angle over the last one, and |λ₂/λ₁|. it opens on the first matrix with v₀ = (1, 0.5), 18.4° from the line y = x. one step turns it to (0.7809, 0.6247), 6.3° away, with the quotient 2.9756; then 2.1°, 0.7°, 0.2°, each about a third of the last, and after 12 steps the vector reads (0.7071, 0.7071) with λ = 3.0000. the slow matrix is still 2.1° away after 12 steps, closing by 0.83 a step. the walk settles on (0.9806, 0.1961), the line through (5, 1), with λ = 1 and the angle shrinking by 0.4 a step. the tie bounces between (0.894, 0.447) and (0.894, −0.447) forever.

### diagonalization

$$
A = P D P^{-1}, \qquad A^n = P D^n P^{-1}
$$

put the eigenvectors in the columns of $P$ and the eigenvalues on the diagonal of $D$. then $AP = PD$, since $A$ times each column is $\lambda$ times that column, and when the eigenvectors span the plane $P$ has an inverse and $A = PDP^{-1}$. the payoff is the powers: $A^2 = PDP^{-1}PDP^{-1} = PD^2P^{-1}$, the inner $P^{-1}P$ cancels every time, and $A^n = PD^nP^{-1}$ with $D^n$ the diagonal matrix of $\lambda^n$. the worked example below gets $A^{10}$ this way, from $3^{10}$, without multiplying $A$ by itself. it needs two independent eigenvectors: a shear has one, and can't be diagonalized.

## worked examples

### a symmetric matrix by hand

$A$ with rows $(2, 1)$ and $(1, 2)$, the movie's matrix. trace 4, determinant 3:

$$
\begin{gathered}
\lambda^2 - 4\lambda + 3 = 0 \\[4pt]
(\lambda - 3)(\lambda - 1) = 0
\end{gathered}
$$

so $\lambda = 3$ and $\lambda = 1$. for $\lambda = 3$, $A - 3I$ has rows $(-1, 1)$ and $(1, -1)$, both saying $y = x$: $v_1 = (1, 1)$. for $\lambda = 1$, $A - I$ has rows $(1, 1)$ and $(1, 1)$, saying $y = -x$: $v_2 = (1, -1)$. check: $A(1, 1) = (3, 3)$ and $A(1, -1) = (1, -1)$. the two directions are perpendicular, $(1, 1) \cdot (1, -1) = 0$, as they always are for a symmetric matrix.

### one that isn't symmetric

rows $(4, 1)$ and $(2, 3)$. trace 7, determinant $12 - 2 = 10$, so $\lambda^2 - 7\lambda + 10 = (\lambda - 5)(\lambda - 2)$ and the eigenvalues are 5 and 2. for $\lambda = 5$, $A - 5I$ has top row $(-1, 1)$: $v_1 = (1, 1)$. for $\lambda = 2$, $A - 2I$ has top row $(2, 1)$: $2x + y = 0$, so $v_2 = (1, -2)$. check: $A(1, -2) = (4 - 2, 2 - 6) = (2, -4) = 2\,(1, -2)$. the two lines aren't perpendicular this time, $(1, 1) \cdot (1, -2) = -1$, and nothing says they should be.

### a shear

rows $(1, 1)$ and $(0, 1)$. trace 2, determinant 1: $\lambda^2 - 2\lambda + 1 = (\lambda - 1)^2$, so $\lambda = 1$, twice. $A - I$ has rows $(0, 1)$ and $(0, 0)$, saying only $y = 0$: the one direction is $(1, 0)$. there's no second one. the repeated root promised two eigenvalues and delivered one line, and that is what a shear looks like: the $x$ axis holds still and everything above it leans.

### a rotation

rows $(0, -1)$ and $(1, 0)$, a quarter turn counter-clockwise. trace 0, determinant 1: $\lambda^2 + 1 = 0$, which has no real roots. no vector in the plane comes back on its own line after a quarter turn. the eigenvalues are $i$ and $-i$, complex numbers, which this page leaves out. among real vectors the answer is: none.

### a two-room walk

a walker is in one of two rooms. each minute, one in room 1 stays with probability 0.9 and moves with 0.1; one in room 2 stays with 0.5 and moves with 0.5. write the shares in each room as a column $(p_1, p_2)$. one minute later the shares are $P(p_1, p_2)$ with

$$
P = \begin{pmatrix} 0.9 & 0.5 \\ 0.1 & 0.5 \end{pmatrix}
$$

trace 1.4, determinant 0.4: $\lambda^2 - 1.4\lambda + 0.4 = (\lambda - 1)(\lambda - 0.4)$, so the eigenvalues are 1 and 0.4. the eigenvector for $\lambda = 1$ is the state nothing changes: $P - I$ has top row $(-0.1, 0.5)$, so $p_1 = 5 p_2$, and with the shares adding to 1 that's $(5/6, 1/6)$. start everyone in room 1, $(1, 0)$, and watch: $(0.9, 0.1)$, then $(0.86, 0.14)$, then $(0.844, 0.156)$. the gap to $5/6$ goes $1/6$, $1/15$, $2/75$, each exactly 0.4 times the one before, because the start is $(5/6, 1/6)$ plus a multiple of the other eigenvector $(1, -1)$, and that part shrinks by $\lambda_2 = 0.4$ every minute. the long-run share is the $\lambda = 1$ eigenvector, and $|\lambda_2|$ says how fast it's reached. the same idea runs a walk on any number of rooms.

### A¹⁰ without ten multiplications

for the movie's matrix, $P$ has columns $(1, 1)$ and $(1, -1)$, $D$ has 3 and 1 on the diagonal, and $P^{-1} = \tfrac{1}{2} P$, since $P^2 = 2I$. then

$$
\begin{aligned}
A^n &= P D^n P^{-1} \\[4pt]
&= \frac{1}{2} \begin{pmatrix} 3^n + 1 & 3^n - 1 \\ 3^n - 1 & 3^n + 1 \end{pmatrix}
\end{aligned}
$$

$n = 1$ gives back rows $(2, 1)$ and $(1, 2)$. $n = 5$ gives $122$ and $121$, and $n = 10$ gives $29{,}525$ on the diagonal and $29{,}524$ off it. the two entries are within 1 of each other because the $(1, -1)$ part never grows: $A^{10}$ is $3^{10}$ times the matrix that projects onto $(1, 1)$, off by $\tfrac{1}{2}$ in each entry.

## the key idea up close

### why det(A − λI) = 0

start from the definition and move $\lambda v$ across:

$$
\begin{gathered}
Av = \lambda v \\[4pt]
Av - \lambda I v = 0 \\[4pt]
(A - \lambda I)\,v = 0
\end{gathered}
$$

the $I$ is there because $A - \lambda$ means nothing: a matrix minus a number. $\lambda I$ is the matrix that scales everything by $\lambda$. so $M = A - \lambda I$ is a matrix that sends the nonzero vector $v$ to the origin. a matrix that does that can't have an inverse: if $M^{-1}$ existed, then $v = M^{-1} M v = M^{-1} 0 = 0$, and $v$ isn't 0. and a matrix with no inverse has determinant 0. the determinant is the factor by which the matrix scales area. $M$ squashes the whole line through $v$ onto one point, so a square with a side along $v$ becomes a segment, with area 0, and the factor is 0. the [linear systems page](/math/linear-systems/) has the same fact from the other side: a system $Mv = 0$ with a nonzero answer is one whose matrix has determinant 0.

that turns a question about vectors into one about a number. for a $2 \times 2$,

$$
\begin{gathered}
\det \begin{pmatrix} a - \lambda & b \\ c & d - \lambda \end{pmatrix} \\[6pt]
= (a - \lambda)(d - \lambda) - bc \\[4pt]
= \lambda^2 - (a + d)\lambda + (ad - bc)
\end{gathered}
$$

a quadratic in $\lambda$, with the trace and the determinant as its coefficients. its discriminant is

$$
\begin{gathered}
(a + d)^2 - 4(ad - bc) \\[4pt]
= (a - d)^2 + 4bc
\end{gathered}
$$

which says when the eigenvalues are real. with $b = c$, the last term is $4b^2 \ge 0$ and the whole thing can't be negative: every symmetric matrix has real eigenvalues. with $bc$ negative enough it goes under 0 and there are none. the rotation has $a = d = 0$ and $bc = -1$, discriminant $-4$. the shear has $a = d = 1$ and $bc = 0$, discriminant 0, the repeated root.

### why a symmetric matrix's eigenlines are perpendicular

let $Av_1 = \lambda_1 v_1$ and $Av_2 = \lambda_2 v_2$ with $\lambda_1 \ne \lambda_2$. for a symmetric $A$, $u \cdot Aw = Au \cdot w$ for any $u$ and $w$: the dot product doesn't care which side the matrix sits on. then

$$
\begin{aligned}
\lambda_2\,(v_1 \cdot v_2) &= v_1 \cdot Av_2 \\[4pt]
&= Av_1 \cdot v_2 \\[4pt]
&= \lambda_1\,(v_1 \cdot v_2)
\end{aligned}
$$

so $(\lambda_1 - \lambda_2)(v_1 \cdot v_2) = 0$, and since the eigenvalues differ, $v_1 \cdot v_2 = 0$: perpendicular. that's why the symmetric cases on this page come out with their eigenlines at right angles, and why a symmetric matrix is a pure stretch along two perpendicular axes, the picture the movie draws.

## in code

`python/math/power_iteration.py` runs power iteration on a $2 \times 2$: apply the matrix, scale back to length 1, repeat, with the rayleigh quotient as the guess at $\lambda$ and the angle to the eigenline as the error. the run starts the movie's matrix from $(1, 0)$, $45°$ off the eigenline $y = x$:

```text
step  λ guess   angle to (1, 1)   ratio
   0   2.0000     45.000°
   1   2.8000     18.435°        0.410
   2   2.9756      6.340°        0.344
   3   2.9973      2.121°        0.335
   4   2.9997      0.707°        0.333
   5   3.0000      0.236°        0.333
```

each step cuts the angle to a third: $|\lambda_2 / \lambda_1| = 1/3$. the first ratio is 0.41 rather than 0.333 because the angle shrinks by exactly a third only once it's small, where the angle and its tangent agree. the $\lambda$ guess is good to four places by step 5. the second run is the tie, rows $(1, 0)$ and $(0, -1)$, from $(1, 0.5)$: the vector goes $(0.894, 0.447)$, $(0.894, -0.447)$, $(0.894, 0.447)$ and so on, forever, and the guess at $\lambda$ sits at 0.6, which is neither eigenvalue. with $|\lambda_1| = |\lambda_2|$ neither part dies away, so nothing settles.

the last lines are what happens without the scaling. $A^{700}(1, 0)$ in doubles is $(\infty, \infty)$: the entries grow like $3^n$, $3^{700}$ is about $10^{334}$, and the largest double, python's `sys.float_info.max`,[^py-float-max] is about $1.8 \times 10^{308}$, so by step 700 the numbers have overflowed. by step 600 they're already $9.4 \times 10^{285}$. the other way round, $(\tfrac{1}{2} I)^{1100}(1, 0)$ comes out as $(0, 0)$: $2^{-1074}$ is the smallest positive double, $5 \times 10^{-324}$, and one more halving is 0. the direction is what power iteration is after, and scaling to length 1 each step keeps the direction and throws the size away.

`python/math/power_iteration.py`

```python
"""power iteration on a 2×2 matrix: apply the matrix to a vector again and again, scale the result back to length 1 each time, and it turns toward the eigenvector with the biggest |λ|, with the rayleigh quotient as the guess at λ. the run prints how the angle left shrinks by about |λ₂/λ₁| a step, what happens when the two biggest |λ| tie, and what the numbers do without the scaling."""

from __future__ import annotations

import math

Vec = tuple[float, float]
Mat = tuple[Vec, Vec]


def matvec(a: Mat, v: Vec) -> Vec:
    """Return Av for a 2×2 matrix given as its rows."""
    return (a[0][0] * v[0] + a[0][1] * v[1], a[1][0] * v[0] + a[1][1] * v[1])


def normalize(v: Vec) -> Vec:
    """Return v scaled to length 1. The zero vector has no direction, so it raises ValueError."""
    n = math.hypot(v[0], v[1])
    if n == 0:
        raise ValueError("the zero vector has no direction")
    return (v[0] / n, v[1] / n)


def rayleigh(a: Mat, v: Vec) -> float:
    """Return (v · Av) / (v · v): the stretch along v, which is λ exactly when v is an eigenvector."""
    av = matvec(a, v)
    return (v[0] * av[0] + v[1] * av[1]) / (v[0] * v[0] + v[1] * v[1])


def eigenvalues(a: Mat) -> tuple[float, float] | None:
    """Return the real eigenvalues, the bigger first, from λ² − (trace)λ + det = 0, or None when there are none."""
    trace = a[0][0] + a[1][1]
    det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
    disc = trace * trace - 4 * det
    if disc < 0:
        return None
    root = math.sqrt(disc)
    return ((trace + root) / 2, (trace - root) / 2)


def angle_to_line(v: Vec, direction: Vec) -> float:
    """Return the angle in degrees, 0 to 90, between v and the line through the origin along direction."""
    u = normalize(v)
    d = normalize(direction)
    return math.degrees(math.asin(min(1.0, abs(u[0] * d[1] - u[1] * d[0]))))


def power_iteration(a: Mat, v0: Vec, steps: int) -> list[tuple[Vec, float]]:
    """Return (vₙ, rayleigh quotient) for n = 0 to steps, each vₙ scaled to length 1.

    vₙ₊₁ is A vₙ, normalized. Writing v₀ as c₁v₁ + c₂v₂ in the eigenvectors, Aⁿv₀ = c₁λ₁ⁿv₁ + c₂λ₂ⁿv₂, so
    the v₂ part shrinks against the v₁ part by |λ₂/λ₁| a step.
    """
    out: list[tuple[Vec, float]] = []
    v = normalize(v0)
    for _ in range(steps + 1):
        out.append((v, rayleigh(a, v)))
        v = normalize(matvec(a, v))
    return out


def convergence(a: Mat, v0: Vec, direction: Vec, steps: int) -> list[tuple[int, float, float, float | None]]:
    """Return (n, λ guess, angle to the eigenline, this angle over the last) for each step of power iteration."""
    rows: list[tuple[int, float, float, float | None]] = []
    prev: float | None = None
    for n, (v, lam) in enumerate(power_iteration(a, v0, steps)):
        angle = angle_to_line(v, direction)
        ratio = angle / prev if prev else None
        rows.append((n, lam, angle, ratio))
        prev = angle
    return rows


def unscaled(a: Mat, v0: Vec, steps: int) -> Vec:
    """Return Aⁿv₀ with no scaling, in doubles: the numbers grow like |λ₁|ⁿ or shrink like it, and a double runs out at about 1e308 and 5e-324."""
    v = (float(v0[0]), float(v0[1]))
    for _ in range(steps):
        v = matvec(a, v)
    return v


def main() -> None:
    sym: Mat = ((2, 1), (1, 2))
    print("A = [[2, 1], [1, 2]], eigenvalues", eigenvalues(sym), "from v0 = (1, 0)")
    print("step  λ guess   angle to (1, 1)   ratio")
    for n, lam, angle, ratio in convergence(sym, (1, 0), (1, 1), 8):
        print(f"{n:4d}  {lam:7.4f}  {angle:9.3f}°  {'' if ratio is None else f'{ratio:11.3f}'}")

    tie: Mat = ((1, 0), (0, -1))
    print("\nA = [[1, 0], [0, -1]], eigenvalues", eigenvalues(tie), "from v0 = (1, 0.5): |λ₁| = |λ₂|")
    for n, (v, lam) in enumerate(power_iteration(tie, (1, 0.5), 4)):
        print(f"{n:4d}  v = ({v[0]:.4f}, {v[1]:.4f})  λ guess {lam:.4f}")

    print("\nwithout scaling, A^700 (1, 0) =", unscaled(sym, (1, 0), 700))
    half: Mat = ((0.5, 0), (0, 0.5))
    print("and (I/2)^1100 (1, 0) =", unscaled(half, (1, 0), 1100))


if __name__ == "__main__":
    main()
```

## pitfalls

- **an eigenvector isn't one vector.** $(1, 1)$, $(2, 2)$ and $(-1, -1)$ are all eigenvectors of the movie's matrix with $\lambda = 3$, and so is every other nonzero multiple. the page writes one and means the line. two answers that differ by a factor are the same answer
- **a matrix can have no real eigenvectors.** a quarter turn has $\lambda^2 + 1 = 0$. it isn't a mistake in the algebra: no direction in the plane survives the turn, and the discriminant $(a - d)^2 + 4bc$ going negative is how the quadratic says so
- **a repeated eigenvalue can come with one direction.** the shear's $\lambda = 1$ is a double root, and $A - I$ has rows $(0, 1)$ and $(0, 0)$, which pin down one line. don't expect two eigenvectors from two roots when the roots coincide, and don't try to diagonalize it
- **power iteration stalls.** when the two biggest $|\lambda|$ are equal, the vector bounces and never settles: rows $(1, 0)$ and $(0, -1)$ from $(1, 0.5)$ flip between $(0.894, 0.447)$ and $(0.894, -0.447)$. and a start with nothing along the dominant direction never turns toward it: $(1, -1)$ under the movie's matrix stays on the $\lambda = 1$ line forever. a random start has some of every direction, which is why it almost always works
- **without scaling, the numbers run away.** $A^{700}(1, 0)$ overflows to $\infty$ for the movie's matrix, and $(\tfrac{1}{2} I)^{1100}(1, 0)$ underflows to 0. scale to length 1 each step
- **$\lambda = 0$ is allowed. $v = 0$ isn't.** rows $(1, 1)$ and $(1, 1)$ send $(1, -1)$ to the origin: an eigenvector with eigenvalue 0, and the sign that the determinant is 0. the zero vector, on the other hand, satisfies $Av = \lambda v$ for every $\lambda$ and says nothing

## practice

1. $A$ has rows $(1, 2)$ and $(2, 1)$. is $(1, 2)$ an eigenvector? is $(1, 1)$?

   **answer:** $A(1, 2) = (1 + 4, 2 + 2) = (5, 4)$, and $(5, 4)$ isn't a multiple of $(1, 2)$: no. $A(1, 1) = (3, 3) = 3\,(1, 1)$: yes, with $\lambda = 3$. the other eigenvector is $(1, -1)$, with $A(1, -1) = (-1, 1) = -1 \cdot (1, -1)$, so $\lambda = -1$.

2. find the eigenvalues and eigenvectors of the matrix with rows $(3, 1)$ and $(0, 2)$.

   **answer:** trace 5, determinant 6: $\lambda^2 - 5\lambda + 6 = (\lambda - 3)(\lambda - 2)$, so $\lambda = 3$ and $2$. a triangular matrix has its eigenvalues on the diagonal, since the determinant of $A - \lambda I$ is the product of the diagonal entries. for $\lambda = 3$, $A - 3I$ has rows $(0, 1)$ and $(0, -1)$, saying $y = 0$: $v_1 = (1, 0)$. for $\lambda = 2$, $A - 2I$ has top row $(1, 1)$, saying $y = -x$: $v_2 = (1, -1)$. check: $A(1, -1) = (3 - 1, -2) = (2, -2) = 2\,(1, -1)$.

3. $A$ has rows $(5, 4)$ and $(1, 2)$. find its eigenvalues two ways: from the quadratic, and from the trace and determinant.

   **answer:** trace 7, determinant $10 - 4 = 6$: $\lambda^2 - 7\lambda + 6 = (\lambda - 6)(\lambda - 1)$, so $\lambda = 6$ and $1$. the check: $6 + 1 = 7$, the trace, and $6 \cdot 1 = 6$, the determinant. two numbers with sum 7 and product 6 are 6 and 1, with no quadratic needed. the eigenvectors are $(4, 1)$, since $A(4, 1) = (24, 6) = 6\,(4, 1)$, and $(1, -1)$, since $A(1, -1) = (1, -1)$. they aren't perpendicular, $(4, 1) \cdot (1, -1) = 3$, because $A$ isn't symmetric.

4. the quarter turn has rows $(0, -1)$ and $(1, 0)$, and the shear has rows $(1, 1)$ and $(0, 1)$. say, from the discriminant and from the picture, why neither has two eigen-directions.

   **answer:** the discriminant is $(a - d)^2 + 4bc$. for the turn, $a = d = 0$ and $bc = -1$: $-4$, under 0, so the quadratic $\lambda^2 + 1$ has no real roots. in the picture, every direction turns by $90°$, so none lands on its own line. for the shear, $a = d = 1$ and $bc = 0$: discriminant 0, one root, $\lambda = 1$, counted twice. in the picture, the $x$ axis holds still and every other line leans over, so there's one eigenline, not two. $A - I$ has rows $(0, 1)$ and $(0, 0)$, which only says $y = 0$.

5. rows $(2, 0)$ and $(0, -3)$. start power iteration at $(1, 1)$. which line does it turn toward, what do the signs do, and how fast does it get there?

   **answer:** the eigenvalues are 2 along the $x$ axis and $-3$ along the $y$ axis, and the size decides: $|{-3}| > 2$, so the $y$ part wins. each step doubles the $x$ part and triples the $y$ part while flipping its sign, so the vector turns toward the $y$ axis while swinging from one side of it to the other: $(1, 1)$, then $(2, -3)$, then $(4, 9)$, then $(8, -27)$, scaled to length 1 each time. the angle to the $y$ axis goes $45°$, $33.7°$, $24.0°$, $16.5°$, $11.2°$, $7.5°$, each about $2/3$ of the last, since $|\lambda_2 / \lambda_1| = 2/3$. the rayleigh quotient heads for $-3$.

6. for the matrix with rows $(2, 1)$ and $(1, 2)$, write $A^n$ in closed form and find $A^5$.

   **answer:** $A = PDP^{-1}$ with $P$'s columns $(1, 1)$ and $(1, -1)$, $D$ the diagonal of 3 and 1, and $P^{-1} = \tfrac{1}{2}P$. so $A^n = PD^nP^{-1} = \tfrac{1}{2} P\,\mathrm{diag}(3^n, 1)\,P$, which multiplies out to $\tfrac{1}{2}(3^n + 1)$ on the diagonal and $\tfrac{1}{2}(3^n - 1)$ off it. $3^5 = 243$, so $A^5$ has 122 on the diagonal and 121 off it: rows $(122, 121)$ and $(121, 122)$. check with $n = 1$: $\tfrac{1}{2}(3 + 1) = 2$ and $\tfrac{1}{2}(3 - 1) = 1$, the matrix itself. and $A^5(1, 0) = (122, 121)$, the first column, is what five applications to $(1, 0)$ give directly.

[^py-float-max]: python's [sys.float_info](https://docs.python.org/3/library/sys.html#sys.float_info) docs: `max` is the largest positive finite float there is, c's `DBL_MAX`.

## related

- https://learning.anthnydas.com/math/matrices.md
- https://learning.anthnydas.com/math/linear-systems.md
- https://learning.anthnydas.com/math/vectors.md
