---
title: "Lab: eigenvalues in code"
heading: Computing eigenvalues, steady states, modes and e^{At}
eyebrow: A7 · Lesson 40 · Lab: eigenvalues in code
xp: 60
---

::: hook
No formula gives the eigenvalues of a large matrix: for 5 × 5 and up, the characteristic polynomial has no solution in radicals, and finding its roots numerically is a poor method anyway. Libraries use iterations instead. In this lab you'll write the simplest one, power iteration, and watch it converge at the rate the eigenvalues set. Then you'll put library eigensolvers to work on lessons 33 to 39: a channel's long-run state, the three normal modes of a chain of coupled tanks, and the matrix exponential, computed so that it works even for the defective matrices eigenvectors can't handle.
:::

::: play
- Power iteration multiplies a vector by $A$ over and over. The part along the top eigenvector grows fastest, and the rest shrinks by $|\lambda_2/\lambda_1|$ each step.
- The curve is the error after $k$ steps, $r^k$, for the ratio $r$ you set. The readout counts the steps to reach $10^{-10}$.
- Push $r$ toward 1, two nearly equal eigenvalues, and convergence slows to a crawl.
:::

```sim plot
view: graph
x: k = 0..80
y: error = 1e-16..1 log
slider: r = 0.05..0.95 step 0.01 = 0.63
plot: r^k | label: error after k steps
marker: error = 1e-10 | label: 10⁻¹⁰
readout: steps to reach 1e-10 = ceil(ln(1e-10)/ln(r)) | digits: 3
```

::: predict
## Power iteration runs on a symmetric matrix with eigenvalues 4.73, 3 and 1.27. By what factor does the error in the Rayleigh-quotient estimate of the top eigenvalue shrink per step?

- [ ] 0.27
- [x] 0.40
- [ ] 0.63
- [ ] 0.73

::: reveal
About 0.40. The vector's error shrinks by $\frac{3}{4.73} = 0.634$ per step, and for a symmetric matrix the Rayleigh quotient $\frac{\mathbf{x}^TA\mathbf{x}}{\mathbf{x}^T\mathbf{x}}$ is accurate to the square of the vector's error, so it improves by $0.634^2 = 0.402$ per step. The eigenvalue reaches $10^{-10}$ accuracy in 24 steps.
:::
:::

::: nameit
## Power iteration

Start from almost any $\mathbf{x}$ and repeat: $\mathbf{x} \leftarrow A\mathbf{x}$, then divide by $|\mathbf{x}|$ so the numbers stay finite. Writing the start in eigenvectors, $A^k\mathbf{x} = c_1\lambda_1^k\mathbf{v}_1 + c_2\lambda_2^k\mathbf{v}_2 + \cdots$, so the direction approaches $\mathbf{v}_1$ with error shrinking like $|\lambda_2/\lambda_1|^k$. The **Rayleigh quotient** $\mathbf{x}^TA\mathbf{x}$ (with $|\mathbf{x}| = 1$) estimates $\lambda_1$. Production eigensolvers use the QR algorithm, a refined relative of this idea.

## Library calls

- `np.linalg.eig(A)` returns eigenvalues and eigenvector columns, complex if necessary, in no particular order.
- `np.linalg.eigh(S)` is for symmetric matrices: real eigenvalues in increasing order and orthonormal eigenvectors, faster and more accurate.

## The matrix exponential by scaling and squaring

$e^{A} = Xe^{\Lambda}X^{-1}$ fails for defective matrices and loses accuracy when $X$ is ill conditioned. The robust method uses the series, made safe by **scaling and squaring**: divide $A$ by $2^s$ until its norm is below about 1, sum a few series terms (they now shrink fast), then square the result $s$ times, since $e^{A} = \left(e^{A/2^s}\right)^{2^s}$. Library versions refine this with Padé approximations.
:::

::: example
## How many steps does power iteration need on $\begin{bmatrix}2 & 1 & 0\\1 & 3 & 1\\0 & 1 & 4\end{bmatrix}$?

::: solution
1. **Eigenvalues.** They are $3 + \sqrt3 = 4.732$, 3 and $3 - \sqrt3 = 1.268$.
2. **Convergence rate.** The Rayleigh quotient's error shrinks per step by
   $$\left(\frac{3}{4.732}\right)^2 = 0.402$$
3. **Track the error.** Starting from $(1, 1, 1)$, the error is 0.105 after one step, 0.0024 after five, and below $10^{-10}$ after 24, where
   $$0.402^{24} \times 0.26 \approx 10^{-10}$$

**Answer:** 24 steps bring the error below $10^{-10}$.
:::
:::

::: example
## Three identical LC tanks in a row are each coupled to their neighbors with $c$ = 0.1, and each has $k$ = 1. What are the mode frequencies?

::: solution
1. **Stiffness matrix.**
   $$K = \begin{bmatrix}k + c & -c & 0\\-c & k + 2c & -c\\0 & -c & k + c\end{bmatrix}$$
2. **Mode frequencies.** The eigenvalues are $k$, $k + c$ and $k + 3c$, so the mode frequencies, in rad/s, are
   $$\begin{aligned} \sqrt1 &= 1 \\ \sqrt{1.1} &= 1.0488 \\ \sqrt{1.3} &= 1.1402 \end{aligned}$$
3. **Mode shapes.** The slowest mode swings all three tanks together, $(1, 1, 1)$; the middle one has the ends opposed and the center still, $(1, 0, -1)$; the fastest has the center against both ends, $(1, -2, 1)$.

**Answer:** 1, 1.0488 and 1.1402 rad/s.
:::
:::

::: check
given: r = 0.5 | 0.8 | 0.9
answer: ceil(ln(1e-10)/ln(r))
tolerance: 0

## A power iteration's error shrinks by {r} per step. How many steps take it from 1 to below $10^{-10}$?

::: right
Right. The first $k$ with $r^k < 10^{-10}$ is {answer}.
:::

::: misses
- [floor(ln(1e-10)/ln(r))] One more: at that step it's still just above $10^{-10}$.
- [any] Not yet. Solve $r^k = 10^{-10}$ and round up.
:::
:::

::: check
given: k = 1 | 4; c = 0.05 | 0.2
answer: sqrt(k + 3*c)
tolerance: 0.5%

## Three tanks in a row have $k$ = {k} and coupling $c$ = {c}. What is the highest mode frequency?

::: right
Right. $\sqrt{k + 3c}$ = {answer}, the mode with the center opposing both ends.
:::

::: misses
- [sqrt(k + 2*c)] That's the frequency of two coupled tanks' opposed mode.
- [sqrt(k + c)] That's the middle mode.
- [any] Not yet. The eigenvalues of $K$ are $k$, $k + c$ and $k + 3c$.
:::
:::

::: check
kind: python

## Write `power(A, steps)` returning the Rayleigh-quotient estimate of the largest eigenvalue after `steps` iterations from $(1, 1, \ldots, 1)$. Set `lam = power(M, 60)` for the matrix in the starter.

```python starter
import numpy as np

M = np.array([[2, 1, 0], [1, 3, 1], [0, 1, 4.0]])

def power(A, steps):
    return np.trace(A) / len(A)

lam = power(M, 60)
print(lam)
```

```python solution
import numpy as np

M = np.array([[2, 1, 0], [1, 3, 1], [0, 1, 4.0]])

def power(A, steps):
    x = np.ones(len(A))
    for _ in range(steps):
        x = A @ x
        x /= np.linalg.norm(x)
    return x @ A @ x

lam = power(M, 60)
print(lam)
```

```python tests
import math
import numpy as np
assert abs(lam - (3 + math.sqrt(3))) < 1e-10, f"The top eigenvalue is 3 + sqrt(3) = 4.7320508; got {lam}."
assert abs(power(np.array([[2.0, 1], [1, 2]]), 60) - 3) < 1e-10, "[[2, 1], [1, 2]] has top eigenvalue 3."
assert abs(power(M, 5) - lam) > 1e-4, "After only 5 steps the estimate should still be visibly off."
```

::: right
Right. Sixty steps is far more than needed here; with $|\lambda_2/\lambda_1|$ near 1 it might not be enough.
:::
:::

::: check
kind: python

## A three-state channel moves between states with the Markov matrix in the starter (its columns sum to 1). Use `np.linalg.eig` to find the steady state, scaled so its entries sum to 1, and set `p`.

```python starter
import numpy as np

P = np.array([[0.8, 0.3, 0.2], [0.15, 0.6, 0.3], [0.05, 0.1, 0.5]])
p = np.ones(3) / 3
print(p)
```

```python solution
import numpy as np

P = np.array([[0.8, 0.3, 0.2], [0.15, 0.6, 0.3], [0.05, 0.1, 0.5]])
lam, V = np.linalg.eig(P)
i = np.argmin(np.abs(lam - 1))
p = np.real(V[:, i])
p = p / p.sum()
print(p)
```

```python tests
import numpy as np
assert np.allclose(P @ p, p), "The steady state is unchanged by P."
assert abs(p.sum() - 1) < 1e-12 and np.all(p > 0), "It should be a probability vector."
assert np.allclose(p, [34 / 59, 18 / 59, 7 / 59]), f"The steady state is (34, 18, 7)/59; got {p}."
```

::: right
Right. The eigenvector for $\lambda = 1$, rescaled: the channel spends 58% of its time in state 1.
:::
:::

::: check
kind: python
given: c = 0.05 | 0.1 | 0.15 | 0.2 | 0.25 | 0.3

## Build $K$ for three tanks in a row with $k$ = 1 and coupling $c$ = {c}, and set `w` to the mode frequencies in increasing order, using `np.linalg.eigh`.

```python starter
import numpy as np

w = np.ones(3)
print(w)
```

```python solution
import numpy as np

k = 1.0
K = np.array([[k + c, -c, 0], [-c, k + 2 * c, -c], [0, -c, k + c]])
w = np.sqrt(np.linalg.eigh(K)[0])
print(w)
```

```python tests
import numpy as np
assert np.allclose(w, np.sqrt([1, 1 + c, 1 + 3 * c])), f"The modes are sqrt(1), sqrt(1 + c) and sqrt(1 + 3c); got {w}."
```

::: right
Right. `eigh` returns the eigenvalues already sorted, and the frequencies are their square roots.
:::
:::

::: check
kind: python

## Write `expm(A)` by scaling and squaring: choose $s$ so that $A/2^s$ has norm below 1, sum 20 terms of the series, then square $s$ times. Set `E1 = expm(np.array([[0, -np.pi], [np.pi, 0]]))` and `E2 = expm(np.array([[1.0, 1], [0, 1]]))`.

```python starter
import numpy as np

def expm(A):
    return np.exp(A)

E1 = expm(np.array([[0, -np.pi], [np.pi, 0]]))
E2 = expm(np.array([[1.0, 1], [0, 1]]))
print(E1, E2, sep="\n")
```

```python solution
import math
import numpy as np

def expm(A):
    A = np.array(A, dtype=float)
    norm = np.abs(A).sum(axis=0).max()
    s = max(0, math.ceil(math.log2(norm)) + 1) if norm > 0 else 0
    B = A / 2**s
    E = np.eye(len(A))
    term = np.eye(len(A))
    for k in range(1, 20):
        term = term @ B / k
        E = E + term
    for _ in range(s):
        E = E @ E
    return E

E1 = expm(np.array([[0, -np.pi], [np.pi, 0]]))
E2 = expm(np.array([[1.0, 1], [0, 1]]))
print(E1, E2, sep="\n")
```

```python tests
import math
import numpy as np
assert np.allclose(E1, -np.eye(2), atol=1e-12), f"Rotating by pi gives -I; got {E1}."
assert np.allclose(E2, math.e * np.array([[1, 1], [0, 1]])), f"The Jordan block gives e [[1, 1], [0, 1]]; got {E2}."
S = np.array([[2.0, 1], [1, 3]]); lam, Q = np.linalg.eigh(S)
assert np.allclose(expm(S), Q @ np.diag(np.exp(lam)) @ Q.T), "On a symmetric matrix it should agree with the eigenvector formula."
```

::: right
Right. The same code handles a rotation, a defective matrix and a symmetric one, which is why it's the method libraries build on.
:::
:::

::: explain
## Why does power iteration find the largest eigenvalue, and what makes it slow?

::: model
Writing the starting vector as a combination of eigenvectors, each multiplication by $A$ multiplies each component by its eigenvalue. After $k$ steps, the component along the largest eigenvalue has grown by $\lambda_1^k$ and the next by $\lambda_2^k$, so relative to the leader every other component shrinks by at least $|\lambda_2/\lambda_1|^k$, and the direction lines up with $\mathbf{v}_1$. The speed is set entirely by that ratio: 0.5 halves the error each step, while 0.99 needs about 2300 steps for ten digits. Two nearly equal eigenvalues are close to indistinguishable to the iteration, which is why practical methods shift the matrix to change the ratio, or use the QR algorithm, which works on all the eigenvalues at once.
:::
:::

::: practice

::: check
given: r = 0.1..0.99
answer: ceil(ln(1e-10)/ln(r))
tolerance: 0

## Steps to $10^{-10}$ at ratio {r}?

::: misses
- [any] Round up $\frac{\ln 10^{-10}}{\ln r}$.
:::
:::

::: check
given: k = 0.5..5; c = 0.01..0.5
answer: sqrt(k + 3*c)
tolerance: 0.5%

## Highest mode of three tanks, $k$ = {k}, $c$ = {c}?

::: misses
- [any] $\sqrt{k + 3c}$.
:::
:::
:::
