---
title: "Lab: floating point and roots in code"
heading: Measuring spacing, summing carefully, and finding polynomial roots
eyebrow: A13 · Lesson 9 · Lab: floating point and roots in code
xp: 60
---

::: hook
Lessons 1 to 8 described floating point, cancellation, conditioning and root finding with formulas. This lab checks each with code. You'll ask NumPy for the spacing of doubles and half-precision numbers, watch a long sum drift and repair it with Kahan's compensated summation, fix a quadratic formula that loses a root, find every root of a cubic by Newton's method with deflation, and watch a polynomial's roots scatter when one coefficient changes in its fifth digit.
:::

::: play
- A sum of n numbers, each rounded to double precision, can drift by up to about $nu$ relative to the total, with $u = 1.1 \times 10^{-16}$; typical drift is closer to $\sqrt n\,u$.
- The curves show both against n, and the flat line shows Kahan summation's bound, which doesn't grow with n.
- At a million terms, naive summation is good to about $10^{-11}$ to $10^{-10}$ relative; Kahan stays near $10^{-16}$.
:::

```sim plot
view: graph
x: n = 10..10000000000 log
y: err = 0.00000000000000001..0.001 log
plot: n*1.1e-16 | label: worst-case naive sum
plot: sqrt(n)*1.1e-16 | label: typical naive sum | color: ch3
plot: 2.2e-16 | label: Kahan bound | color: ch2 | dashed
```

::: predict
## In double precision, you add 0.1 to a running total one million times. How far is the result from 100 000?

- [ ] Exactly 0
- [x] About $10^{-6}$
- [ ] About $10^{-16}$
- [ ] About 1

::: reveal
About $1.3 \times 10^{-6}$. Each addition rounds the growing total to its spacing, which near $10^5$ is $1.5 \times 10^{-11}$, and the roundings mostly lean the same way, because 0.1 itself isn't exact in binary. Kahan's compensated sum, or `math.fsum`, carries the lost low-order bits along and lands on the correctly rounded total.
:::
:::

::: nameit
## Tools

- `np.spacing(x)` gives the gap from x to the next representable number of x's type; `np.float16(x)`, `np.float32(x)` make lower-precision values.
- `math.fsum` adds a list of floats exactly and rounds once.
- `np.poly(roots)` builds coefficients from roots, and `np.roots(coeffs)` finds roots through the companion matrix.

## Kahan summation

Keep a correction c of what the last addition lost:

```
y = x - c;  t = s + y;  c = (t - s) - y;  s = t
```

In exact arithmetic c would be 0; in floating point, $(t - s) - y$ recovers the low-order part of y that didn't fit into t, to be added back next time.

## Newton with deflation

Run Newton's method with Horner's rule on the polynomial, divide out the root found, repeat on the quotient, and polish each root with a couple of Newton steps on the original polynomial.
:::

::: example
## What are the spacings of doubles near 1 and 1000, and of half-precision numbers near 1 and 1000?

::: solution
1. **Doubles.** `np.spacing(1.0)` is $2.22 \times 10^{-16}$ and `np.spacing(1000.0)` is $1.14 \times 10^{-13}$: the same 53 significant bits, scaled by the power of two.
2. **Half precision.** `np.spacing(np.float16(1))` is $9.77 \times 10^{-4}$ and `np.spacing(np.float16(1000))` is 0.5.
3. **What that does to a sum.** A float16 accumulator holding a total near 1000 can't register an increment of 0.2: it rounds back to the same value. That's the stalled-clock problem of lesson 1, in a format used for neural network training.

**Answer:** doubles are spaced $2.22 \times 10^{-16}$ near 1 and $1.14 \times 10^{-13}$ near 1000; half-precision numbers are spaced $9.77 \times 10^{-4}$ near 1 and 0.5 near 1000.
:::
:::

::: example
## Compute the small root of $x^2 - 10^8x + 1 = 0$ two ways.

::: solution
1. **The textbook formula.**
   $$\frac{10^8 - \sqrt{10^{16} - 4}}{2} = 7.45 \times 10^{-9}$$
   That's wrong by 25%: the square root equals $10^8$ to almost every digit, and the subtraction leaves only rounding noise.
2. **The large root first.** It has no cancellation:
   $$\frac{10^8 + \sqrt{10^{16} - 4}}{2} = 10^8$$
3. **The small root from the product of the roots.**
   $$\frac{c}{x_\text{big}} = 10^{-8}$$
   This is correct to full precision.

**Answer:** the textbook formula gives $7.45 \times 10^{-9}$, wrong by 25%; dividing c by the large root gives $10^{-8}$, correct to full precision.
:::
:::

::: check
given: p = 11 | 24 | 53; x = 50 | 1000
answer: 2^(floor(log(x)/log(2)) + 1 - p)
tolerance: 0.5%

## What does `np.spacing` return for x = {x} in a format with {p} significant bits?

::: right
Right. The gap above x, $2^{e + 1 - p}$, where $2^e \le x < 2^{e+1}$.
:::

::: misses
- [2^(1 - p)] That's the spacing at 1; it scales with x's power of two.
- [any] Find the power of two just below x first.
:::
:::

::: check
given: b = 1000000 | 100000000; c = 1 | 2
answer: c/((b + sqrt(b^2 - 4*c))/2)
tolerance: 0.5%

## What is the small root of $x^2 - \given{b}x + \given{c} = 0$, computed stably?

::: right
Right. Find the big root without cancellation, then divide c by it.
:::

::: misses
- [c/b^2] The big root is about b, so the small one is about $c/b$.
- [any] $x_\text{small} = \frac{c}{x_\text{big}}$.
:::
:::

::: check
kind: python

## Add 0.1 one million times, naively into `naive` and with Kahan's compensated summation into `kahan`. Set `exact` to `math.fsum([0.1] * 1000000)`.

```python starter
import math

naive = kahan = 0.0
exact = math.fsum([0.1] * 1000000)
print(naive - 100000, kahan - 100000)
```

```python solution
import math

naive = 0.0
for _ in range(1000000):
    naive += 0.1

kahan, c = 0.0, 0.0
for _ in range(1000000):
    y = 0.1 - c
    t = kahan + y
    c = (t - kahan) - y
    kahan = t

exact = math.fsum([0.1] * 1000000)
print(naive - 100000, kahan - 100000)
```

```python tests
assert abs(naive - exact) > 1e-7, f"The naive sum should drift by about 1e-6; got {naive - exact}."
assert abs(kahan - exact) < 1e-10, f"Kahan's sum should match fsum; got {kahan - exact}."
```

::: right
Right. The naive total is off by $1.3 \times 10^{-6}$; Kahan's matches the exactly rounded sum.
:::
:::

::: check
kind: python

## Write `small_root(b, c)` returning the small root of $x^2 - bx + c = 0$ (b > 0) without cancellation. Set `bad` to the textbook formula's value for $b = 10^8$, c = 1, and `good` to yours.

```python starter
import math

def small_root(b, c):
    return (b - math.sqrt(b * b - 4 * c)) / 2

bad = (1e8 - math.sqrt(1e16 - 4)) / 2
good = small_root(1e8, 1.0)
print(bad, good)
```

```python solution
import math

def small_root(b, c):
    big = (b + math.sqrt(b * b - 4 * c)) / 2
    return c / big

bad = (1e8 - math.sqrt(1e16 - 4)) / 2
good = small_root(1e8, 1.0)
print(bad, good)
```

```python tests
assert abs(good - 1e-8) < 1e-22, f"The small root is 1e-8 to full precision; got {good}."
assert abs(bad - 1e-8) > 1e-9, "The textbook formula should be visibly wrong here."
assert abs(small_root(3.0, 2.0) - 1.0) < 1e-15, "x^2 - 3x + 2 has roots 1 and 2."
```

::: right
Right. $10^{-8}$ exactly, against the textbook formula's $7.45 \times 10^{-9}$.
:::
:::

::: check
kind: python

## Write `horner(a, x)` returning $(p(x), p'(x))$ for coefficients a (highest power first) and `deflate(a, r)` returning the quotient after dividing by $x - r$. Find all roots of $x^3 - 6x^2 + 11x - 6$ by Newton from 0 with deflation, polishing each on the original. Set `roots`.

```python starter
def horner(a, x):
    return 0.0, 1.0

def deflate(a, r):
    return a[:-1]

roots = []
print(roots)
```

```python solution
def horner(a, x):
    p, d = a[0], 0.0
    for co in a[1:]:
        d = d * x + p
        p = p * x + co
    return p, d

def deflate(a, r):
    q = [a[0]]
    for co in a[1:-1]:
        q.append(q[-1] * r + co)
    return q

a = [1.0, -6.0, 11.0, -6.0]
cur, roots = a[:], []
while len(cur) > 2:
    x = 0.0
    for _ in range(50):
        p, d = horner(cur, x)
        x -= p / d
    for _ in range(3):
        p, d = horner(a, x)
        x -= p / d
    roots.append(x)
    cur = deflate(cur, x)
roots.append(-cur[1] / cur[0])
print(roots)
```

```python tests
assert horner([2, -6, 2, -1], 3) == (5, 20), "Horner on 2x^3 - 6x^2 + 2x - 1 at 3 gives (5, 20)."
assert sorted(round(r, 9) for r in roots) == [1.0, 2.0, 3.0], f"The roots are 1, 2 and 3; got {roots}."
```

::: right
Right. 1, 2 and 3, each to about $10^{-15}$; the smallest is found first, which keeps deflation accurate.
:::
:::

::: check
kind: python

## Build the coefficients of $(x + 1)(x + 2)\cdots(x + 8)$ with `np.poly`, add 0.0005 to the $x^7$ coefficient, and find the roots with `np.roots`. Set `leftmost` to the real part of the leftmost root and `max_imag` to the largest imaginary part.

```python starter
import numpy as np

leftmost = -8.0
max_imag = 0.0
print(leftmost, max_imag)
```

```python solution
import numpy as np

p = np.poly(-np.arange(1, 9))
p[1] += 0.0005
r = np.roots(p)
leftmost = r.real.min()
max_imag = np.abs(r.imag).max()
print(leftmost, max_imag)
```

```python tests
assert abs(leftmost + 8.1605) < 1e-3, f"The root at -8 moves to about -8.16; got {leftmost}."
assert abs(max_imag - 0.4516) < 1e-3, f"The roots at -6 and -7 become -6.50 +/- 0.45j; got {max_imag}."
```

::: right
Right. A change in the fifth significant digit of one coefficient moved a root by 0.16 and turned two real roots into a complex pair.
:::
:::

::: check
kind: python

## Set `s1` and `s1000` to `np.spacing` of 1.0 and 1000.0 in float64, and `h1` and `h1000` to the same in float16. Then set `stuck` to `True` if adding `np.float16(0.2)` to `np.float16(1000)` leaves it unchanged.

```python starter
import numpy as np

s1 = s1000 = h1 = h1000 = 0.0
stuck = False
print(s1, s1000, h1, h1000, stuck)
```

```python solution
import numpy as np

s1, s1000 = np.spacing(1.0), np.spacing(1000.0)
h1, h1000 = np.spacing(np.float16(1)), np.spacing(np.float16(1000))
stuck = bool(np.float16(1000) + np.float16(0.2) == np.float16(1000))
print(s1, s1000, h1, h1000, stuck)
```

```python tests
assert s1 == 2.0**-52 and s1000 == 2.0**-43, f"Double spacing is 2^-52 at 1 and 2^-43 at 1000; got {s1}, {s1000}."
assert float(h1) == 2.0**-10 and float(h1000) == 0.5, f"Half precision spacing is 2^-10 at 1 and 0.5 at 1000; got {h1}, {h1000}."
assert stuck, "Near 1000 a float16 can't change by 0.2."
```

::: right
Right. Near 1000, half precision steps by 0.5, so an increment of 0.2 rounds away entirely.
:::
:::

::: explain
## Why does Kahan's correction $c = (t - s) - y$ capture exactly what an addition lost?

::: model
When s and y are added, the result t keeps only the high-order part of the true sum; the low-order bits of y that fall below t's last place are rounded away. Subtracting s from t then recovers the part of y that actually made it into t, and this subtraction is exact, because t and s are close. Subtracting y from that leaves minus the part of y that was lost, again exactly in typical cases. Feeding that correction into the next addition puts the lost bits back, so the running sum carries an extra word of precision and the error no longer grows with the number of terms.
:::
:::

::: practice

::: check
given: p = 24 | 53; x = 8 | 100
answer: 2^(floor(log(x)/log(2)) + 1 - p)
tolerance: 0.5%

## Spacing near {x} with {p} bits?

::: misses
- [any] $2^{e + 1 - p}$.
:::
:::

::: check
given: b = 10000 | 1000000000; c = 3 | 0.5
answer: c/((b + sqrt(b^2 - 4*c))/2)
tolerance: 0.5%

## Stable small root of $x^2 - \given{b}x + \given{c}$?

::: misses
- [any] $c/x_\text{big}$.
:::
:::
:::
