---
title: "Lab: linear algebra in code"
heading: LU with pivoting, Cholesky, iterative refinement, Jacobi against CG, and the SVD
eyebrow: A13 · Lesson 35 · Lab: linear algebra in code
xp: 60
---

::: hook
Lessons 23 to 34 covered direct solvers, iterative solvers, eigenvalues and the SVD. In this lab you'll write the two classic factorizations yourself and check them against NumPy, recover float64 accuracy from a float32 factorization, race Jacobi against conjugate gradients on the model problem, and confirm that the truncated SVD's error is exactly the first singular value left out.
:::

::: play
- On the 1D model problem with N unknowns, Jacobi's error shrinks by $\cos\frac{\pi}{N + 1}$ per sweep, and CG finishes in at most N steps (here N/2, by symmetry of the right-hand side).
- The curves show each method's iteration count for a $10^{-8}$ residual against N. Jacobi grows as $N^2$, CG as N.
- At N = 50, Jacobi takes thousands of sweeps and CG 25 steps.
:::

```sim plot
view: graph
x: N = 10..1000 log
y: iterations = 1..10000000 log
plot: ln(1e-8)/ln(cos(pi/(N + 1))) | label: Jacobi sweeps (estimate)
plot: N/2 | label: CG steps | color: ch3
```

::: predict
## A float32 factorization of a matrix with κ = $10^4$ is used with float64 iterative refinement. After three refinement steps, about how accurate is the solution?

- [ ] About $10^{-4}$, float32's limit for this κ
- [x] About $10^{-12}$, float64's limit for this κ
- [ ] About $10^{-16}$
- [ ] It doesn't improve

::: reveal
About $10^{-12}$ to $10^{-13}$: float64's own limit, $\kappa u_{64}$. The first solve is good to about $3 \times 10^{-5}$, and each refinement step multiplies the error by about $\kappa u_{32} \approx 6 \times 10^{-4}$ until it reaches that floor.
:::
:::

::: nameit
## Writing the factorizations

- **LU with partial pivoting:** for each column k, find the largest entry at or below the diagonal, swap that row up (record it in a permutation and swap the finished part of L too), then eliminate below. NumPy row swaps: `A[[k, p]] = A[[p, k]]`.
- **Cholesky:** column by column, $l_{jj} = \sqrt{a_{jj} - \sum_{k<j}l_{jk}^2}$ and $l_{ij} = \frac{a_{ij} - \sum_{k<j}l_{ik}l_{jk}}{l_{jj}}$.

Test against the definitions: $\max\lvert PA - LU\rvert$ should be at rounding level, and all $\lvert l_{ij}\rvert \le 1$ with pivoting.

## Refinement in mixed precision

Factor or solve in float32 (`A.astype(np.float32)`), compute residuals $r = b - Ax$ in float64, solve for the correction in float32, and add it in float64.

## CG in a few lines

$x = 0$, $r = p = b$; repeat: $\alpha = \frac{r^Tr}{p^TAp}$, $x \mathrel{+}= \alpha p$, $r_\text{new} = r - \alpha Ap$, $p = r_\text{new} + \frac{r_\text{new}^Tr_\text{new}}{r^Tr}p$.
:::

::: example
## Refine a float32 solution of a 50 × 50 system with κ = $10^4$ and x = (1, …, 1).

::: solution
1. **The float32 solve.** Its worst error is $3.1 \times 10^{-5}$.
2. **Refine.** After one refinement step it's $3.1 \times 10^{-10}$, and after two $4.5 \times 10^{-13}$. Further steps hover around $3 \times 10^{-13}$ to $5 \times 10^{-13}$, the float64 floor for this κ.
3. **The rate.** The ratio from step to step, about $10^{-5}$, is close to $\kappa u_{32}$.
4. **The limit.** If κ were $10^8$, $\kappa u_{32}$ would exceed 1 and refinement would diverge: mixed precision works only for matrices that float32 can factor meaningfully.

**Answer:** the worst error falls from $3.1 \times 10^{-5}$ to $3.1 \times 10^{-10}$ and then $4.5 \times 10^{-13}$, the float64 floor, in two steps.
:::
:::

::: example
## Solve the 1D model problem with N = 50 and b = 1 by Jacobi and by CG, to a relative residual of $10^{-8}$.

::: solution
1. **Jacobi.** It takes 9653 sweeps, at a rate per sweep of
   $$\cos\frac{\pi}{51} = 0.9981$$
2. **CG.** It takes 25 steps.
3. **Why so few.** In exact arithmetic CG finishes in at most as many steps as the matrix has distinct eigenvalues that the right-hand side touches; b = 1 is symmetric about the middle, so only the 25 symmetric modes are involved.
4. **The work.** Each CG step costs a matrix–vector product and a few vector operations, about twice a Jacobi sweep, so CG wins here by a factor of almost 200.

**Answer:** 9653 Jacobi sweeps against 25 CG steps, almost 200 times less work for CG.
:::
:::

::: check
given: N = 20 | 50 | 100; d = 6 | 8
answer: d*ln(10)/(-ln(cos(pi/(N + 1))))
tolerance: 1%

## About how many Jacobi sweeps reduce the error of the 1D model problem with N = {N} unknowns by $10^{\given{d}}$?

::: right
Right. The rate is $\cos\frac{\pi}{N + 1}$, so the count is $\frac{d\ln 10}{-\ln\cos\frac{\pi}{N + 1}} \approx \frac{2d\ln 10}{\pi^2}(N + 1)^2$.
:::

::: misses
- [d*ln(10)/(-ln(cos(pi/N)))] Use $N + 1$: the grid spacing is $\frac{1}{N + 1}$.
- [any] $\rho = \cos\frac{\pi}{N + 1}$.
:::
:::

::: check
given: k = 100 | 10000; s = 1 | 2
answer: (k*6e-8)^(s + 1)
tolerance: 1%

## A float32 solve of a system with κ = {k} is refined {s} times in float64. About how small is the error, before reaching float64's floor?

::: right
Right. Each solve, the first one included, contributes a factor of about $\kappa u_{32}$.
:::

::: misses
- [(k*6e-8)^s] The first solve already has error $\kappa u_{32}$.
- [any] $(\kappa u_{32})^{s + 1}$.
:::
:::

::: check
kind: python

## Write `lu_pp(A)` returning `(P, L, U)` with $A[P] = LU$, using partial pivoting. Test it on `np.random.default_rng(0).standard_normal((6, 6))`: set `resid` to $\max\lvert A[P] - LU\rvert$ and `lmax` to $\max\lvert l_{ij}\rvert$.

```python starter
import numpy as np

def lu_pp(A):
    n = len(A)
    return np.arange(n), np.eye(n), A.copy()

A = np.random.default_rng(0).standard_normal((6, 6))
P, L, U = lu_pp(A)
resid = np.max(np.abs(A[P] - L @ U))
lmax = np.max(np.abs(L))
print(resid, lmax)
```

```python solution
import numpy as np

def lu_pp(A):
    A = A.astype(float).copy()
    n = len(A)
    P, L = np.arange(n), np.eye(n)
    for k in range(n - 1):
        p = k + np.argmax(np.abs(A[k:, k]))
        if p != k:
            A[[k, p]] = A[[p, k]]
            P[[k, p]] = P[[p, k]]
            L[[k, p], :k] = L[[p, k], :k]
        for i in range(k + 1, n):
            L[i, k] = A[i, k] / A[k, k]
            A[i, k:] -= L[i, k] * A[k, k:]
    return P, L, np.triu(A)

A = np.random.default_rng(0).standard_normal((6, 6))
P, L, U = lu_pp(A)
resid = np.max(np.abs(A[P] - L @ U))
lmax = np.max(np.abs(L))
print(resid, lmax)
```

```python tests
import numpy as np
assert resid < 1e-14, f"PA should equal LU to rounding; got a residual of {resid}."
assert lmax <= 1 + 1e-15, f"With partial pivoting every multiplier is at most 1; got {lmax}."
assert np.allclose(np.tril(L), L) and np.allclose(np.triu(U), U), "L must be lower and U upper triangular."
```

::: right
Right. The residual is at rounding level and no multiplier exceeds 1, which is what keeps elimination stable.
:::
:::

::: check
kind: python

## Write `chol(A)` returning the lower-triangular Cholesky factor. Test it on $M = BB^T + 5I$ with `B = np.random.default_rng(1).standard_normal((5, 5))`: set `diff` to the largest difference from `np.linalg.cholesky(M)`.

```python starter
import numpy as np

def chol(A):
    return np.eye(len(A))

B = np.random.default_rng(1).standard_normal((5, 5))
M = B @ B.T + 5 * np.eye(5)
diff = np.max(np.abs(chol(M) - np.linalg.cholesky(M)))
print(diff)
```

```python solution
import numpy as np
import math

def chol(A):
    n = len(A)
    L = np.zeros((n, n))
    for j in range(n):
        L[j, j] = math.sqrt(A[j, j] - np.dot(L[j, :j], L[j, :j]))
        for i in range(j + 1, n):
            L[i, j] = (A[i, j] - np.dot(L[i, :j], L[j, :j])) / L[j, j]
    return L

B = np.random.default_rng(1).standard_normal((5, 5))
M = B @ B.T + 5 * np.eye(5)
diff = np.max(np.abs(chol(M) - np.linalg.cholesky(M)))
print(diff)
```

```python tests
import numpy as np
assert diff < 1e-13, f"Your factor should match NumPy's; got a difference of {diff}."
L = chol(np.array([[4.0, 2.0], [2.0, 3.0]]))
assert abs(L[1, 1] - np.sqrt(2)) < 1e-15, "The factor of [[4, 2], [2, 3]] has sqrt(2) in its corner."
```

::: right
Right. It matches NumPy to rounding, with half of LU's arithmetic and no pivoting.
:::
:::

::: check
kind: python

## Build a 50 × 50 symmetric matrix with singular values from 1 down to $10^{-4}$ (`Q, _ = np.linalg.qr(rng.standard_normal((50, 50)))` with `rng = np.random.default_rng(2)`, then `A = (Q * np.logspace(0, -4, 50)) @ Q.T`) and b = A·ones. Solve in float32, refine four times in float64, and set `errs` to the five worst errors.

```python starter
import numpy as np

errs = [1.0] * 5
print(errs)
```

```python solution
import numpy as np

rng = np.random.default_rng(2)
Q, _ = np.linalg.qr(rng.standard_normal((50, 50)))
A = (Q * np.logspace(0, -4, 50)) @ Q.T
x_true = np.ones(50)
b = A @ x_true
A32 = A.astype(np.float32)
x = np.linalg.solve(A32, b.astype(np.float32)).astype(np.float64)
errs = [np.max(np.abs(x - x_true))]
for _ in range(4):
    r = b - A @ x
    d = np.linalg.solve(A32, r.astype(np.float32)).astype(np.float64)
    x = x + d
    errs.append(np.max(np.abs(x - x_true)))
print(errs)
```

```python tests
assert errs[0] > 1e-7, f"The float32 solve alone should be off by about 1e-5; got {errs[0]}."
assert errs[2] < 1e-10, f"Two refinement steps should reach about 1e-12; got {errs[2]}."
assert errs[4] < 1e-11, f"Refinement should settle at float64's floor; got {errs[4]}."
```

::: right
Right. From about $10^{-5}$ to about $10^{-13}$ in two steps, using float32 for every solve.
:::
:::

::: check
kind: python

## On the 1D model matrix T (2 on the diagonal, −1 beside it) with N = 50 and b = 1, count Jacobi sweeps `jac` and CG steps `cg` until $\lVert b - Tx\rVert \le 10^{-8}\lVert b\rVert$, starting from zero.

```python starter
import numpy as np

jac = cg = 0
print(jac, cg)
```

```python solution
import numpy as np

N = 50
T = 2 * np.eye(N) - np.eye(N, k=1) - np.eye(N, k=-1)
b = np.ones(N)
tol = 1e-8 * np.linalg.norm(b)

x = np.zeros(N)
jac = 0
while np.linalg.norm(b - T @ x) > tol:
    x = (b + np.r_[x[1:], 0] + np.r_[0, x[:-1]]) / 2
    jac += 1

x = np.zeros(N)
r = b.copy()
p = r.copy()
cg = 0
while np.linalg.norm(r) > tol:
    Ap = T @ p
    alpha = (r @ r) / (p @ Ap)
    x += alpha * p
    r_new = r - alpha * Ap
    p = r_new + (r_new @ r_new) / (r @ r) * p
    r = r_new
    cg += 1
print(jac, cg)
```

```python tests
assert 9000 < jac < 10500, f"Jacobi should need about 9650 sweeps; got {jac}."
assert cg <= 26, f"CG should finish in about 25 steps; got {cg}."
```

::: right
Right. About 9650 sweeps against 25 steps.
:::
:::

::: check
kind: python

## Take the SVD of `M = np.random.default_rng(3).standard_normal((40, 30))`, form the rank-5 truncation, and set `err` to its 2-norm error and `s6` to the sixth singular value.

```python starter
import numpy as np

M = np.random.default_rng(3).standard_normal((40, 30))
err = s6 = 0.0
print(err, s6)
```

```python solution
import numpy as np

M = np.random.default_rng(3).standard_normal((40, 30))
U, s, Vt = np.linalg.svd(M, full_matrices=False)
k = 5
Mk = (U[:, :k] * s[:k]) @ Vt[:k]
err = np.linalg.norm(M - Mk, 2)
s6 = s[k]
print(err, s6)
```

```python tests
assert s6 > 1, f"The sixth singular value of this matrix is about 8; got {s6}."
assert abs(err - s6) < 1e-10, f"Eckart-Young: the error equals sigma_6; got {err} and {s6}."
```

::: right
Right. The rank-5 error is exactly $\sigma_6$, as Eckart–Young says.
:::
:::

::: explain
## Why must partial pivoting also swap the already-computed part of L when it swaps rows?

::: model
The multipliers in L record which multiple of each pivot row was subtracted from each other row. When a later column's pivot search swaps two rows, those rows' identities change from that step on, but the multipliers already computed for them belong to the rows, not to the positions. Swapping the finished columns of L along with the rows keeps each stored multiplier attached to the row it was computed for, so that at the end L times U reproduces the rows of A in the final permuted order. Forgetting the swap gives an L and U whose product is a different matrix, with a residual far above rounding.
:::
:::

::: practice

::: check
given: N = 10 | 200; d = 4 | 10
answer: d*ln(10)/(-ln(cos(pi/(N + 1))))
tolerance: 1%

## Jacobi sweeps for N = {N}, {d} digits?

::: misses
- [any] Rate $\cos\frac{\pi}{N + 1}$.
:::
:::

::: check
given: k = 1000 | 50; s = 2 | 1
answer: (k*6e-8)^(s + 1)
tolerance: 1%

## Error after {s} refinements, κ = {k}?

::: misses
- [any] $(\kappa u_{32})^{s + 1}$.
:::
:::
:::
