---
title: Conditioning and numerical error
heading: When a correct algorithm gives a wrong answer
eyebrow: A7 · Lesson 52 · Conditioning
xp: 50
---

::: hook
Fit a polynomial of degree 11 through 12 calibration points and solve for its coefficients with a perfectly good solver: the coefficients can come out wrong in every digit, even though plugging them back in reproduces the data almost exactly. Nothing is broken. Some problems are **ill-conditioned**: tiny changes in the data, even rounding at the sixteenth digit, produce large changes in the answer. A single number, the **condition number**, tells you in advance how many digits you can trust.
:::

::: play
- The two lines are $x + y = 2$ and $x + (1 + e)y = 2 + \delta$. When $e$ is small they're nearly parallel.
- $\delta$ is a small error in the right-hand side, such as a measurement error. Watch where the crossing point goes as you change it.
- Shrink $e$. The same small $\delta$ moves the solution much farther. The readout gives the condition number.
:::
:::

```sim plot
view: graph
x: x = -6..10
y: y = -6..8
slider: e = 0.02..1 step 0.01 = 0.2
slider: dl = -0.1..0.1 step 0.01 = 0.05
plot: 2 - x | label: x + y = 2
plot: (2 + dl - x)/(1 + e) | label: x + (1 + e)y = 2 + δ | color: ch2
readout: y = dl/e | digits: 4
readout: x = 2 - dl/e | digits: 4
readout: condition number = sqrt(((2 + (1 + e)^2 + 1) + sqrt((3 + (1 + e)^2)^2 - 4*e^2))/((3 + (1 + e)^2) - sqrt((3 + (1 + e)^2)^2 - 4*e^2))) | digits: 4
```

::: predict
## A matrix has condition number $10^{10}$. Solving with it in double precision (about 16 digits), roughly how many correct digits can you expect?

- [ ] 16
- [ ] 10
- [x] About 6
- [ ] None

::: reveal
About 6. Rounding errors of relative size $10^{-16}$ can be amplified by up to $\kappa = 10^{10}$, giving relative errors near $10^{-6}$. A useful rule: you lose about $\log_{10}\kappa$ digits.
:::
:::

::: nameit
## The condition number

For a square invertible matrix,

$$\kappa(A) = \frac{\sigma_{\max}}{\sigma_{\min}} = \|A\|\,\|A^{-1}\|$$

If $\mathbf{b}$ changes by a relative amount $\varepsilon$, the solution of $A\mathbf{x} = \mathbf{b}$ can change by up to $\kappa\varepsilon$:

$$\frac{\|\Delta\mathbf{x}\|}{\|\mathbf{x}\|} \le \kappa(A)\,\frac{\|\Delta\mathbf{b}\|}{\|\mathbf{b}\|}$$

$\kappa \ge 1$ always; orthogonal matrices have $\kappa = 1$, perfectly conditioned. Conditioning is a property of the **problem**, not of the algorithm: no method can recover digits the data doesn't determine.

## Stability is a property of the algorithm

A **stable** algorithm gives the exact answer to a nearby problem. Elimination with partial pivoting, QR and the SVD are stable; elimination without pivoting is not (a tiny pivot creates huge multipliers, lesson 9). A stable algorithm on a well-conditioned problem gives an accurate answer. On an ill-conditioned problem even a stable algorithm loses about $\log_{10}\kappa$ digits.

## Residual and error

The **residual** $\mathbf{r} = \mathbf{b} - A\hat{\mathbf{x}}$ is easy to compute; the **error** $\hat{\mathbf{x}} - \mathbf{x}$ is what you care about. A stable solver always makes the residual tiny. For an ill-conditioned $A$ that says little about the error: nearly parallel lines meet almost anywhere along their length while staying very close to both.

## Familiar trouble spots

- **Hilbert matrices**, $h_{ij} = \frac{1}{i + j - 1}$: $\kappa \approx 10^{13}$ at size 10.
- **Polynomial fitting** in the basis $1, x, x^2, \ldots$ (Vandermonde matrices) on many points; orthogonal polynomials fix it.
- **Normal equations** $A^TA$: $\kappa(A^TA) = \kappa(A)^2$, which is why QR is preferred (lesson 28).
- **Circuits** with resistances spanning many orders of magnitude, like 1 mΩ next to 1 GΩ.
:::

::: example
## How sensitive is the system $x + y = 2$, $x + 1.001y = 2$ to errors in $\mathbf{b}$?

::: solution
1. **The solution.** It's $(2, 0)$.
2. **Nudge $\mathbf{b}$.** Change the second right side to $2.001$ and the solution becomes $(1, 1)$: a change of 0.04% in $\mathbf{b}$ moved the solution by about 70% of its size.
3. **Condition number.** The condition number of $\begin{bmatrix}1 & 1\\1 & 1.001\end{bmatrix}$ is about 4000, so an amplification of about two thousand is within what it allows.

**Answer:** very sensitive: a 0.04% change in $\mathbf{b}$ moves the solution by about 70%, and the condition number is about 4000.
:::
:::

::: example
## Solve $H\mathbf{x} = H\mathbf{1}$ with the 10 × 10 Hilbert matrix. How accurate is the answer?

::: solution
1. **Condition number.** `np.linalg.cond` gives $\kappa = 1.6 \times 10^{13}$.
2. **Residual and error.** Solving gives a residual of about $4 \times 10^{-16}$, as small as rounding allows, yet the largest error in $\mathbf{x}$ is about $3 \times 10^{-4}$.
3. **Digits lost.** That's roughly 13 of the 16 digits gone, as $\log_{10}\kappa = 13.2$ predicts.
4. **At size 12.** There $\kappa \approx 2 \times 10^{16}$ and the answer has no correct digits at all.

**Answer:** only about 3 digits are right: the largest error is about $3 \times 10^{-4}$, even though the residual is about $4 \times 10^{-16}$.
:::
:::

::: example
## A solver works in double precision on a matrix with condition number $10^6$. About how many digits of the answer can you trust?

::: solution
1. **Precision.** Double precision carries about 16 significant digits.
2. **Relative error.** A stable solver's relative error is about the condition number times the rounding unit:
   $$10^6 \times 10^{-16} = 10^{-10}$$
   so roughly 10 digits are right.
3. **The residual.** $|A\hat{\mathbf{x}} - \mathbf{b}|$ will still look tiny, near $10^{-16}$ relative to $|\mathbf{b}|$. It measures how well the answer fits the equations, and the condition number turns that into how close the answer is.

**Answer:** about 10 digits.
:::
:::

::: check
given: k = 1e6 | 1e10 | 1e12
answer: 16 - log(k)
tolerance: 2%

## A matrix has condition number {k}. In double precision (16 digits), about how many correct digits does solving with it leave?

::: right
Right. About $16 - \log_{10}\kappa$ = {answer}.
:::

::: misses
- [log(k)] That's how many digits are lost.
- [16] The condition number amplifies rounding errors; digits are lost.
- [any] Not yet. Subtract $\log_{10}\kappa$ from 16.
:::
:::

::: check
given: s1 = 50 | 200; s2 = 0.5 | 0.01
answer: s1/s2
tolerance: 0.5%

## A matrix's largest singular value is {s1} and its smallest is {s2}. What is its condition number?

::: right
Right. $\kappa = \sigma_{\max}/\sigma_{\min}$ = {answer}.
:::

::: misses
- [s2/s1] Largest over smallest; $\kappa \ge 1$.
- [s1 - s2] It's a ratio.
- [any] Not yet. $\sigma_{\max}/\sigma_{\min}$.
:::
:::

::: check
given: k = 100 | 1000; eps = 0.1 | 0.01
answer: k*eps

## $\kappa(A)$ = {k} and $\mathbf{b}$ has a {eps}% error. What is the largest possible percent error in $\mathbf{x}$?

::: right
Right. Up to $\kappa\varepsilon$ = {answer}%.
:::

::: misses
- [eps] The condition number amplifies the error.
- [any] Not yet. Multiply by $\kappa$.
:::
:::

::: check
given: k = 1e3 | 1e5 | 1e8
answer: k^2

## $\kappa(A)$ = {k}. What is the condition number of $A^TA$?

::: right
Right. $\kappa(A^TA) = \kappa(A)^2$ = {answer}: forming the normal equations squares the sensitivity.
:::

::: misses
- [k] Squaring: the singular values of $A^TA$ are $\sigma_i^2$.
- [2*k] The singular values are squared, so their ratio is squared.
- [any] Not yet. What are the singular values of $A^TA$?
:::
:::

::: check
given: e = 0.01 | 0.001; d = 0.02 | 0.005
answer: d/e

## Solve $x + y = 2$, $x + (1 + \given{e})y = 2 + \given{d}$. What is $y$?

::: right
Right. Subtracting the equations gives $\given{e}\,y = \given{d}$, so $y$ = {answer}.
:::

::: misses
- [d] Divide by the small difference {e}.
- [e/d] Upside down.
- [any] Not yet. Subtract the first equation from the second.
:::
:::

::: check
kind: python
given: n = 6 | 8 | 10

## Build the {n} × {n} Hilbert matrix `H` ($h_{ij} = \frac{1}{i + j + 1}$ with 0-based indices), set `kappa` to its condition number, solve `H @ x = H @ ones` with `np.linalg.solve`, and set `err` to the largest error in the solution and `res` to the largest entry of the residual.

```python starter
import numpy as np

H = np.zeros((n, n))
kappa = 0.0
err = 0.0
res = 0.0
print(kappa, err, res)
```

```python solution
import numpy as np

H = np.array([[1 / (i + j + 1) for j in range(n)] for i in range(n)])
kappa = np.linalg.cond(H)
ones = np.ones(n)
b = H @ ones
x = np.linalg.solve(H, b)
err = np.max(np.abs(x - ones))
res = np.max(np.abs(H @ x - b))
print(kappa, err, res)
```

```python tests
import numpy as np
assert np.isclose(H[0, 0], 1) and np.isclose(H[1, 2], 1/4), "h[i, j] = 1/(i + j + 1), so H[0, 0] = 1 and H[1, 2] = 1/4."
assert np.isclose(kappa, np.linalg.cond(H)), "kappa should be np.linalg.cond(H)."
assert res < 1e-14, "The residual should be tiny: the solver is stable."
assert err > 100 * res, "The error should be far bigger than the residual: that's ill-conditioning."
assert err < kappa * 1e-14, "The error shouldn't exceed what the condition number allows."
```

::: right
Right. The residual is at rounding level while the error is many orders of magnitude bigger, and $\log_{10}\kappa$ predicts how many digits were lost.
:::
:::

::: check
kind: parts
given: d = 0.001 | 0.01 | 0.1; e = 0.001 | 0.003

## Solve $x + y = 2$, $x + (1 + \given{d})y = 2 + \given{e}$.

::: part
answer: e/d
tolerance: 0.5%

### What is $y$?

::: misses
- [e] Divide by the second pivot, {d}.
- [any] Subtract the rows: $dy = e$.
:::
:::

::: part
answer: 2 - e/d
tolerance: 0.5%

### What is $x$?

::: misses
- [any] $x = 2 - y$.
:::
:::
:::

::: check
kind: derivation
vars: k = 1..1e12

## A stable solver runs in double precision on a matrix with condition number $k$.

::: step
answer: k*1.1e-16

### With a rounding unit of $1.1 \times 10^{-16}$, about how large is the relative error?
:::

::: step
answer: 16 - log(k)

### About how many correct digits remain?
:::

::: right
Right. Each factor of 10 in the condition number costs about one digit.
:::
:::

::: explain
## A solver returns $\hat{\mathbf{x}}$ with a residual of $10^{-16}$. Why might $\hat{\mathbf{x}}$ still be badly wrong?

::: model
A tiny residual means $A\hat{\mathbf{x}}$ is very close to $\mathbf{b}$, so $\hat{\mathbf{x}}$ exactly solves a slightly perturbed problem. If $A$ is ill-conditioned, very different vectors give almost the same $A\mathbf{x}$: for nearly parallel lines, points far apart along the lines are all close to both. So a small residual can coexist with a large error, up to about $\kappa$ times the relative residual. Only a well-conditioned matrix turns a small residual into a small error.
:::
:::

::: practice

::: check
given: k = 1e3 | 1e4 | 1e6 | 1e9 | 1e10 | 1e12
answer: log(k)
tolerance: 2%

## A matrix has condition number {k}. About how many decimal digits are lost solving with it?

::: misses
- [16 - log(k)] That's how many remain.
- [any] $\log_{10}\kappa$.
:::
:::

::: check
kind: choice

## What is the condition number of an orthogonal matrix?

- [x] 1
- [ ] 0
- [ ] Infinite
- [ ] It depends on the matrix

::: misses
- [2] The smallest possible value is 1.
- [any] All its singular values are 1.
:::
:::

::: check
given: s1 = 10 | 40; k = 100 | 1000
answer: s1/k
tolerance: 0.5%

## A matrix has $\sigma_{\max}$ = {s1} and condition number {k}. What is $\sigma_{\min}$?

::: misses
- [s1*k] $\kappa = \sigma_{\max}/\sigma_{\min}$.
- [any] $\sigma_{\max}/\kappa$.
:::
:::
:::
