---
title: "Lab: derivatives from numbers"
heading: How a computer finds a slope, and how it goes wrong
eyebrow: A5 · Lesson 12 · Lab: derivatives from numbers
xp: 60
---

::: hook
A computer can't take a limit. When a simulator needs a slope, or a scope computes the current through a capacitor from its sampled voltage, it divides a small difference by a small step. Make the step too big and the answer is off because the curve bends; make it too small and the answer is off because the computer rounds. In this lab you'll write the difference formulas in Python, find the step that balances those two errors, and turn a sampled voltage into a current.
:::

::: play
- The curve is the error of a central difference for the slope of $e^x$ at $x = 1$, against the step $h$, on log axes. The dashed line is the truncation error, $\frac{h^2}{6}e$; the dotted line is the rounding error, about $\frac{\varepsilon e}{h}$ with $\varepsilon = 2.2 \times 10^{-16}$.
- The total error is smallest where the two lines cross. Below that, a smaller step makes things worse.
- Change how many digits the computer keeps (the exponent of $\varepsilon$) and watch the best step move.
:::

```sim plot
view: graph
x: h = 1e-12..1 log
y: error = 1e-12..1 log
slider: d = 4..16 step 1 = 16
plot: 2.718*h^2/6 + 2.2*10^(-d)*2.718/h | samples: 400 | label: total error
plot: 2.718*h^2/6 | dashed | color: ch2 | label: truncation
plot: 2.2*10^(-d)*2.718/h | dashed | color: ch3 | label: rounding
readout: best step = (3*2.2*10^(-d))^(1/3) | digits: 3
```

::: predict
## A central difference for the slope of $e^x$ at 1 is tried with $h = 10^{-4}$ and with $h = 10^{-12}$, in standard double precision. Which is more accurate?

- [x] $h = 10^{-4}$, by a wide margin
- [ ] $h = 10^{-12}$, since a smaller step is closer to the limit
- [ ] They're about the same
- [ ] Neither: both are exact

::: reveal
$h = 10^{-4}$, by about seven digits. Its error is the truncation error, $\frac{h^2}{6}e \approx 4.5 \times 10^{-9}$. At $h = 10^{-12}$, the two function values agree in their first 12 digits, so their difference keeps only about 4 good digits, and dividing by the tiny $2h$ magnifies the rounding: the error is around $10^{-4}$. The best step for a central difference in double precision is near $10^{-5}$.
:::
:::

::: nameit
## Difference formulas

- **Forward:** $f'(x) \approx \frac{f(x + h) - f(x)}{h}$, with error about $\frac h2f''$: it shrinks in proportion to $h$.
- **Central:** $f'(x) \approx \frac{f(x + h) - f(x - h)}{2h}$, with error about $\frac{h^2}{6}f'''$: it shrinks as $h^2$, because the even terms cancel.

## Rounding

A double-precision number keeps about 16 significant digits ($\varepsilon \approx 2.2 \times 10^{-16}$). Each function value carries a rounding error near $\varepsilon|f|$, and the difference formula divides it by $h$. So the total error of a central difference is about

$$\frac{h^2}{6}|f'''| + \frac{\varepsilon|f|}{h}$$

which is smallest near $h \approx \varepsilon^{1/3}$, about $6 \times 10^{-6}$ for values near 1.

## Sampled data

When the data are samples $v_0, v_1, \ldots$ taken every $\Delta t$, the step is fixed. The central difference at sample $k$ is $\frac{v_{k+1} - v_{k-1}}{2\Delta t}$; the first and last samples need a one-sided formula, or are dropped. Noise in the samples is divided by $2\Delta t$ too, so differentiating noisy data magnifies the noise; that's why scopes smooth before they differentiate.

In Python, lists hold the samples, and a list comprehension builds the differences: `[(v[k+1] - v[k-1]) / (2*dt) for k in range(1, len(v) - 1)]`.
:::

::: example
## Estimate the slope of $\sin x$ at $x = 1$ with $h = 0.1$, forward and central. (The true slope is $\cos 1 = 0.540\,302$.)

::: solution
1. **Forward difference.**
   $$\begin{aligned} m &= \frac{\sin 1.1 - \sin 1}{0.1} \\ &= \frac{0.891\,207 - 0.841\,471}{0.1} \\ &= 0.497\,364 \end{aligned}$$
   an error of $-0.0429$.
2. **Central difference.**
   $$\begin{aligned} m &= \frac{\sin 1.1 - \sin 0.9}{0.2} \\ &= \frac{0.891\,207 - 0.783\,327}{0.2} \\ &= 0.539\,402 \end{aligned}$$
   an error of $-0.000\,900$.
3. **Compare.** For the same step, the central difference is almost 50 times better, as the $h$ against $h^2$ errors predict.

**Answer:** the forward difference gives 0.497 364 (error $-0.0429$) and the central difference gives 0.539 402 (error $-0.000\,900$), almost 50 times better.
:::
:::

::: example
## A 10 µF capacitor's voltage is sampled every 1 ms: 2.00, 2.18, 2.33 V. Estimate the current at the middle sample.

::: solution
1. **Slope at the middle sample.** Use the central difference:
   $$\begin{aligned} \frac{dv}{dt} &\approx \frac{2.33 - 2.00}{2 \times 0.001} \\ &= 165\ \text{V/s} \end{aligned}$$
2. **Current.**
   $$\begin{aligned} i &= C\frac{dv}{dt} \\ &= 10^{-5} \times 165 \\ &= 1.65\ \text{mA} \end{aligned}$$
3. **Effect of noise.** If each reading had a 0.01 V error, the slope could be off by
   $$\frac{0.02}{0.002} = 10\ \text{V/s}$$
   6% of the answer: the noise is magnified by $1/(2\Delta t)$.

**Answer:** about 1.65 mA flows at the middle sample.
:::
:::

::: check
given: h = 0.1 | 0.01 | 0.001
answer: h^2/6*exp(1)
tolerance: 1%

## About how big is the truncation error of a central difference for the slope of $e^x$ at $x = 1$ with $h$ = {h}?

::: right
Right. $\frac{h^2}{6}f'''(1) = \frac{h^2}{6}e$ = {answer}.
:::

::: misses
- [h/2*exp(1)] That's the forward difference's error.
- [any] Not yet. The central error is about $\frac{h^2}{6}f'''$.
:::
:::

::: check
given: dv = 0.2 | 0.33 | 0.5; dt = 0.5 | 1; C = 1 | 10
answer: C*1e-6*dv/(2*dt*1e-3)
unit: A
tolerance: 0.5%

## A {C} µF capacitor's voltage is sampled every {dt} ms. Two samples on either side of a moment differ by {dv} V. What current flows at that moment?

::: right
Right. $C\frac{\Delta v}{2\Delta t}$ = {answer}.
:::

::: misses
- [C*1e-6*dv/(dt*1e-3)] The two samples are two steps apart: divide by $2\Delta t$.
- [any] Not yet. Central difference, then $i = C\,dv/dt$.
:::
:::

::: check
kind: python

## Write `forward(f, x, h)` and `central(f, x, h)`, the two difference formulas. The tests compare their errors for $\sin$ at 1.

```python starter
import math

def forward(f, x, h):
    return 0

def central(f, x, h):
    return 0

print(forward(math.sin, 1, 0.1), central(math.sin, 1, 0.1), math.cos(1))
```

```python solution
import math

def forward(f, x, h):
    return (f(x + h) - f(x)) / h

def central(f, x, h):
    return (f(x + h) - f(x - h)) / (2 * h)

print(forward(math.sin, 1, 0.1), central(math.sin, 1, 0.1), math.cos(1))
```

```python tests
import math
ef = abs(forward(math.sin, 1, 0.1) - math.cos(1))
ec = abs(central(math.sin, 1, 0.1) - math.cos(1))
assert abs(ef - 0.0429385) < 1e-6, f"The forward error at h = 0.1 is 0.0429; got {ef}."
assert abs(ec - 0.0009001) < 1e-6, f"The central error at h = 0.1 is 0.00090; got {ec}."
assert central(lambda x: x**2, 3, 0.5) == 6, "A central difference is exact for a parabola."
assert abs(central(math.sin, 1, 0.05) - math.cos(1)) < ec / 3.9, "Halving h should cut the central error by about 4."
```

::: right
Right. Halve $h$ and the forward error halves while the central error quarters.
:::
:::

::: check
kind: python

## Write `best_step(f, df, x)`, which tries the steps $10^{-1}, 10^{-2}, \ldots, 10^{-13}$ in a central difference and returns the one whose error against the exact slope `df(x)` is smallest. Set `h = best_step(math.exp, math.exp, 1.0)`.

```python starter
import math

def best_step(f, df, x):
    return 1e-13

h = best_step(math.exp, math.exp, 1.0)
print(h)
```

```python solution
import math

def best_step(f, df, x):
    best, best_err = None, float("inf")
    for k in range(1, 14):
        h = 10.0 ** -k
        err = abs((f(x + h) - f(x - h)) / (2 * h) - df(x))
        if err < best_err:
            best, best_err = h, err
    return best

h = best_step(math.exp, math.exp, 1.0)
print(h)
```

```python tests
import math
assert 1e-7 <= h <= 1e-4, f"For e^x at 1 the best step is near 1e-5 or 1e-6; got {h}."
h2 = best_step(math.sin, math.cos, 0.5)
assert 1e-7 <= h2 <= 1e-4, f"For sin at 0.5 the best step is in the same range; got {h2}."
e_best = abs((math.exp(1 + h) - math.exp(1 - h)) / (2 * h) - math.e)
e_tiny = abs((math.exp(1 + 1e-12) - math.exp(1 - 1e-12)) / 2e-12 - math.e)
assert e_best < e_tiny / 100, "The best step should beat a tiny step like 1e-12 by a wide margin."
```

::: right
Right. The best step sits where truncation and rounding errors are equal, near the cube root of the machine precision.
:::
:::

::: check
kind: python
given: C = 1 | 10 | 47

## The starter has voltage samples `v` of a {C} µF capacitor taken every `dt` = 1 ms. Write `current(v, dt, C)` returning the list of currents at the interior samples, $C\frac{v_{k+1} - v_{k-1}}{2\Delta t}$, with `C` in farads. Set `i = current(v, 1e-3, C * 1e-6)`.

```python starter
import math
v = [5 * (1 - math.exp(-k / 20)) for k in range(101)]

def current(v, dt, C):
    return []

i = current(v, 1e-3, C * 1e-6)
print(i[:3])
```

```python solution
import math
v = [5 * (1 - math.exp(-k / 20)) for k in range(101)]

def current(v, dt, C):
    return [C * (v[k + 1] - v[k - 1]) / (2 * dt) for k in range(1, len(v) - 1)]

i = current(v, 1e-3, C * 1e-6)
print(i[:3])
```

```python tests
import math
assert len(i) == 99, f"There are 99 interior samples; got {len(i)}."
exact = [C * 1e-6 * 5 / 0.02 * math.exp(-k / 20) for k in range(1, 100)]
worst = max(abs(a - b) / b for a, b in zip(i, exact))
assert worst < 0.001, f"With a 20 ms time constant and 1 ms samples, the central differences should be within 0.1% of C dv/dt; worst {worst:.4%}."
assert current([0, 1, 4, 9], 1, 2) == [4.0, 8.0], "current([0, 1, 4, 9], 1, 2) should be [4.0, 8.0]."
```

::: right
Right. That's what a scope's math channel does to show a capacitor's current from its voltage.
:::
:::

::: check
kind: python
given: s = 0.001 | 0.005 | 0.02

## Noise hurts differences. The starter adds random noise of size `s` = {s} V to samples of $\sin(2\pi \cdot 50t)$ taken every 0.1 ms. Set `raw` to the largest error of the central differences against the exact slope, and `smooth` to the largest error after first averaging each sample with its two neighbors (a three-point moving average) and then differencing.

```python starter
import math, random
random.seed(1)
dt = 1e-4
t = [k * dt for k in range(400)]
v = [math.sin(2 * math.pi * 50 * x) + random.gauss(0, s) for x in t]

raw = 0
smooth = 0
print(raw, smooth)
```

```python solution
import math, random
random.seed(1)
dt = 1e-4
t = [k * dt for k in range(400)]
v = [math.sin(2 * math.pi * 50 * x) + random.gauss(0, s) for x in t]

def slope_errors(v, start):
    out = []
    for k in range(1, len(v) - 1):
        d = (v[k + 1] - v[k - 1]) / (2 * dt)
        exact = 2 * math.pi * 50 * math.cos(2 * math.pi * 50 * t[start + k])
        out.append(abs(d - exact))
    return out

raw = max(slope_errors(v, 0))
avg = [(v[k - 1] + v[k] + v[k + 1]) / 3 for k in range(1, len(v) - 1)]
smooth = max(slope_errors(avg, 1))
print(raw, smooth)
```

```python tests
assert raw > smooth, f"Averaging first should reduce the error; got raw {raw:.1f}, smooth {smooth:.1f}."
assert raw > 2 * s / (2 * 1e-4), "Noise of size s can move a difference by about s / dt."
assert smooth < raw / 1.5, "A three-point average should cut the worst error noticeably."
```

::: right
Right. Averaging first trades a little lag for much less noise, the same trade every real differentiator makes.
:::
:::

::: check
kind: python

## Write `richardson(f, x, h)`, which combines two central differences, $D(h)$ and $D(h/2)$, into $\frac{4D(h/2) - D(h)}{3}$. Since the central error goes as $h^2$, this cancels it. Set `e_central` and `e_rich` to the errors for the slope of $e^x$ at 1 with $h = 0.1$.

```python starter
import math

def richardson(f, x, h):
    return (f(x + h) - f(x - h)) / (2 * h)

e_central = abs((math.exp(1.1) - math.exp(0.9)) / 0.2 - math.e)
e_rich = abs(richardson(math.exp, 1.0, 0.1) - math.e)
print(e_central, e_rich)
```

```python solution
import math

def richardson(f, x, h):
    D = lambda s: (f(x + s) - f(x - s)) / (2 * s)
    return (4 * D(h / 2) - D(h)) / 3

e_central = abs((math.exp(1.1) - math.exp(0.9)) / 0.2 - math.e)
e_rich = abs(richardson(math.exp, 1.0, 0.1) - math.e)
print(e_central, e_rich)
```

```python tests
import math
assert e_rich < e_central / 1000, f"Richardson should be thousands of times better here; got {e_central:.2e} and {e_rich:.2e}."
assert abs(richardson(lambda x: x**4, 1.0, 0.5) - 4) < 1e-12, "It's exact for quartics: the slope of x^4 at 1 is 4."
assert abs(richardson(math.sin, 0.5, 0.2) - math.cos(0.5)) < 1e-5, "It should get the slope of sin at 0.5 to better than 1e-5 with h = 0.2."
```

::: right
Right. Combining two estimates whose errors you know the shape of is one of the most useful tricks in numerical work.
:::
:::

::: explain
## Why does making the step smaller eventually make a numerical derivative worse?

::: model
A difference quotient has two errors that pull in opposite directions. The truncation error comes from the curve bending within the step; it shrinks as $h$ (forward) or $h^2$ (central). The rounding error comes from the computer storing each function value to about 16 digits: when $h$ is tiny, $f(x + h)$ and $f(x - h)$ agree in most of their digits, their difference keeps only the last few, and dividing by the tiny $h$ magnifies that loss. Rounding error grows as $1/h$. So the total error falls as $h$ shrinks, reaches a minimum where the two are equal, then rises. For a central difference in double precision the best step is near $10^{-5}$, and steps below that give worse answers.
:::
:::

::: practice

::: check
given: h = 0.0001..0.5
answer: h^2/6*exp(1)
tolerance: 1%

## Central-difference truncation error for $e^x$ at 1, $h$ = {h}?

::: misses
- [any] $\frac{h^2}{6}e$.
:::
:::

::: check
given: C = 0.1..100; dv = 0.01..2; dt = 0.01..10
answer: C*1e-6*dv/(2*dt*1e-3)
tolerance: 0.5%

## Current: {C} µF, samples {dt} ms apart, $\Delta v$ = {dv} V across two steps?

::: misses
- [any] $C\frac{\Delta v}{2\Delta t}$.
:::
:::
:::
