---
title: Numerical derivatives and integrals
heading: Slopes and areas from samples
eyebrow: A4 · Lesson 39 · Numerical derivatives and integrals
xp: 40
---

::: hook
A scope gives you samples, not formulas. To get the current through a capacitor from its sampled voltage, you need $C\,dv/dt$: a derivative from samples. To get the charge delivered by a sampled current, or the energy from sampled power, you need an integral. Both are simple ideas (a slope between neighbors, a sum of thin slices), but how accurately they work depends on the step size in ways that surprise people, including a step that's too small.
:::

::: predict
## You estimate the derivative of $\sin x$ at $x = 1$ with $\frac{\sin(1 + h) - \sin(1 - h)}{2h}$. Which $h$ gives the most accurate answer in double precision?

- [ ] $h = 10^{-1}$
- [x] $h = 10^{-5}$
- [ ] $h = 10^{-12}$
- [ ] The smaller the better

::: reveal
About $10^{-5}$. Shrinking $h$ reduces the formula's error, which goes as $h^2$, but the two sines become nearly equal and their difference loses digits to rounding, an error that grows as $10^{-16}/h$. The total is smallest where the two balance, near $h \approx 10^{-5}$, with an error around $10^{-11}$. At $h = 10^{-12}$ the rounding error is about $10^{-5}$, a million times worse.
:::
:::

::: nameit
## Derivatives

From samples spaced $h$ apart:

$$\text{forward:}\ \frac{f(x + h) - f(x)}{h} \qquad \text{central:}\ \frac{f(x + h) - f(x - h)}{2h}$$

Taylor series (A6) show their errors: about $\frac{h}{2}f''$ for forward and $\frac{h^2}{6}f'''$ for central. Central differences are far more accurate for the same $h$. In NumPy, `np.diff(v) / dt` gives forward differences between samples and `np.gradient(v, dt)` gives central differences inside the array.

**Rounding sets a floor.** Each value of $f$ carries a rounding error of about $10^{-16}$ of itself, and dividing a difference by a small $h$ magnifies it. Noise in measured data is much larger than $10^{-16}$, so derivatives of real measurements are noisy unless the data is smoothed first.

## Integrals

To integrate samples $y_0, y_1, \ldots, y_n$ spaced $h$ apart:

**Trapezoid rule:** join neighbors with straight lines and add the trapezoids.

$$\int y\,dx \approx h\left(\tfrac{1}{2}y_0 + y_1 + \cdots + y_{n-1} + \tfrac{1}{2}y_n\right)$$

Its error goes as $h^2$: halve the step and the error drops by four.

**Simpson's rule** (with $n$ even): fit parabolas through each pair of slices.

$$\int y\,dx \approx \frac{h}{3}\left(y_0 + 4y_1 + 2y_2 + 4y_3 + \cdots + 4y_{n-1} + y_n\right)$$

Its error goes as $h^4$: halving the step cuts it sixteenfold.

**Running integrals.** `np.cumsum(y) * h` is a quick running sum (rectangles); for a running trapezoid integral, add each new trapezoid, $h(y_{k-1} + y_k)/2$, to the total.

## Checking accuracy

The order of a method shows up when you halve the step: the error ratio is $2^p$ for an order-$p$ method. That's how you test that an implementation is correct, and how you estimate the error of a result when there's no exact answer to compare with.
:::

::: example
## A capacitor of 1 µF has $v = 5\sin(2\pi \cdot 50\,t)$ volts across it, sampled every 0.1 ms. Estimate the current at $t = 2$ ms.

::: solution
1. **Write the current as a derivative.** $i = C\,dv/dt$, estimated with the central difference:
   $$i \approx C\,\frac{v(t + h) - v(t - h)}{2h}$$

```
import numpy as np
v = lambda t: 5 * np.sin(2 * np.pi * 50 * t)
h = 1e-4
i = 1e-6 * (v(2e-3 + h) - v(2e-3 - h)) / (2 * h)
print(i)          # 1.27059e-03
```

2. **Compare with the exact value.**
   $$\begin{aligned} i &= C \cdot 5 \cdot 2\pi \cdot 50 \\ &\quad \times \cos(2\pi \cdot 50 \cdot 0.002) \\ &= 1.27080\ \text{mA} \end{aligned}$$
   so the estimate is 0.016% low.
3. **Explain the error.** The step is a two-hundredth of a period, and the error goes as
   $$\frac{(\omega h)^2}{6} = 0.00016$$

**Answer:** about 1.27059 mA, 0.016% below the exact 1.27080 mA.
:::
:::

::: example
## A current $i = 2e^{-t/5\text{ ms}}$ A flows for 20 ms. How much charge is delivered? Compare the trapezoid rule with 20 steps against the exact answer.

::: solution
1. **Apply the trapezoid rule.** With 20 steps: the sum of the samples, minus half of the two ends, times the step.

```
t = np.linspace(0, 20e-3, 21)
i = 2 * np.exp(-t / 5e-3)
h = t[1] - t[0]
Q = h * (i.sum() - (i[0] + i[-1]) / 2)
exact = 2 * 5e-3 * (1 - np.exp(-4))
print(Q, exact)       # 0.0098495, 0.0098168
```

2. **The exact charge.**
   $$\begin{aligned} Q &= 2 \times 5\ \text{ms} \times (1 - e^{-4}) \\ &= 0.0098168\ \text{C} \end{aligned}$$
3. **Compare.** The trapezoid rule's 0.0098495 C overestimates by 0.33% here, because the curve sags below each straight segment.
4. **Halve the step.** Doubling the steps cuts the error to 0.083%, a quarter, as an $h^2$ method should.

**Answer:** the exact charge is 0.0098168 C, and the trapezoid rule with 20 steps gives 0.0098495 C, 0.33% high.
:::
:::

::: check
kind: python
given: x0 = 0.5 | 1 | 2; h = 0.1 | 0.01

## Set `fwd` and `ctr` to the forward and central difference estimates of the derivative of $\sin x$ at `x0` = {x0} with step `h` = {h}, and `e_fwd`, `e_ctr` to their absolute errors against $\cos x_0$.

```python starter
import math
fwd = ctr = 0
e_fwd = e_ctr = 0
print(e_fwd, e_ctr)
```

```python solution
import math
fwd = (math.sin(x0 + h) - math.sin(x0)) / h
ctr = (math.sin(x0 + h) - math.sin(x0 - h)) / (2 * h)
e_fwd = abs(fwd - math.cos(x0))
e_ctr = abs(ctr - math.cos(x0))
print(e_fwd, e_ctr)
```

```python tests
import math
assert abs(fwd - (math.sin(x0 + h) - math.sin(x0)) / h) < 1e-12, "fwd is (f(x+h) − f(x))/h."
assert abs(ctr - (math.sin(x0 + h) - math.sin(x0 - h)) / (2 * h)) < 1e-12, "ctr is (f(x+h) − f(x−h))/(2h)."
assert e_ctr < e_fwd, "The central difference should be the more accurate."
```
:::

::: check
kind: python
given: x0 = 0.4 | 0.7 | 1 | 1.3 | 2 | 2.5

## For $h = 10^{-1}, 10^{-2}, \ldots, 10^{-13}$, compute the central difference error for $\sin$ at `x0` = {x0}. Set `errs` to the list of 13 errors and `best_h` to the $h$ with the smallest one.

```python starter
import math
hs = [10.0**-p for p in range(1, 14)]
errs = []
best_h = hs[-1]
print(best_h)
```

```python solution
import math
hs = [10.0**-p for p in range(1, 14)]
errs = [abs((math.sin(x0 + h) - math.sin(x0 - h)) / (2 * h) - math.cos(x0)) for h in hs]
best_h = hs[errs.index(min(errs))]
print(best_h)
```

```python tests
import math
hs = [10.0**-p for p in range(1, 14)]
want = [abs((math.sin(x0 + h) - math.sin(x0 - h)) / (2 * h) - math.cos(x0)) for h in hs]
assert len(errs) == 13 and all(abs(a - b) < 1e-15 for a, b in zip(errs, want)), "errs should hold the 13 central-difference errors in order."
assert 1e-7 <= best_h <= 1e-3, "best_h should be where the error is smallest, in the middle of the range: too large an h has truncation error, too small has rounding error."
```
:::

::: check
kind: python
given: I0 = 1 | 2; tau = 2 | 5; n = 10 | 20 | 40

## Integrate $i = I_0 e^{-t/\tau}$ (`I0` = {I0} A, `tau` = {tau} ms) from 0 to $4\tau$ with the trapezoid rule on `n` = {n} steps. Set `Q` to the charge in coulombs and `err` to its relative error against the exact $I_0\tau(1 - e^{-4})$.

```python starter
import numpy as np
Q = 0
err = 0
print(Q, err)
```

```python solution
import numpy as np
t = np.linspace(0, 4 * tau * 1e-3, n + 1)
i = I0 * np.exp(-t / (tau * 1e-3))
h = t[1] - t[0]
Q = h * (i.sum() - (i[0] + i[-1]) / 2)
exact = I0 * tau * 1e-3 * (1 - np.exp(-4))
err = abs(Q - exact) / exact
print(Q, err)
```

```python tests
import numpy as np
t = np.linspace(0, 4 * tau * 1e-3, n + 1)
i = I0 * np.exp(-t / (tau * 1e-3))
h = t[1] - t[0]
want = h * (i.sum() - (i[0] + i[-1]) / 2)
assert abs(Q - want) < 1e-12 * want, "Q should be the trapezoid sum: h times (all the samples, with the two ends counted half)."
exact = I0 * tau * 1e-3 * (1 - np.exp(-4))
assert abs(err - abs(want - exact) / exact) < 1e-9, "err should be |Q − exact| / exact."
```
:::

::: check
kind: python
given: n = 4 | 8 | 16

## Write `simpson(y, h)` for an odd number of samples (an even number of slices), and set `S` to the integral of $\sin x$ from 0 to $\pi$ on `n` = {n} slices, and `err` to its error against the exact 2.

```python starter
import numpy as np

def simpson(y, h):
    return h * y.sum()

x = np.linspace(0, np.pi, n + 1)
S = simpson(np.sin(x), x[1] - x[0])
err = abs(S - 2)
print(S, err)
```

```python solution
import numpy as np

def simpson(y, h):
    return h / 3 * (y[0] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum() + y[-1])

x = np.linspace(0, np.pi, n + 1)
S = simpson(np.sin(x), x[1] - x[0])
err = abs(S - 2)
print(S, err)
```

```python tests
import numpy as np
x = np.linspace(0, 1, 5)
assert abs(simpson(x**3, 0.25) - 0.25) < 1e-12, "Simpson's rule is exact for cubics: simpson of x³ on [0, 1] with 4 slices should be 0.25. The weights are 1, 4, 2, 4, ..., 4, 1, times h/3."
xx = np.linspace(0, np.pi, n + 1)
want = (xx[1] - xx[0]) / 3 * (np.sin(xx[0]) + 4 * np.sin(xx[1:-1:2]).sum() + 2 * np.sin(xx[2:-1:2]).sum() + np.sin(xx[-1]))
assert abs(S - want) < 1e-12, "S doesn't match Simpson's rule on this grid."
```
:::

::: check
kind: python
given: A = 1 | 2 | 5; n = 20 | 50 | 200; shape = 0 | 1 | 2

## The starter samples one period of a waveform `v` at `n` + 1 = {n} + 1 equally spaced points (the first and last are the same point in the cycle). Using the trapezoid rule written with NumPy slices (not a library integrator), set `rms` to $\sqrt{\frac{1}{T}\int_0^T v^2\,dt}$. Then set `exact` to the known value: $A/\sqrt2$ for a sine, $A$ for a square wave and $A/\sqrt3$ for a triangle.

```python starter
import numpy as np
T = 1e-3
t = np.linspace(0, T, n + 1)
x = t / T
v = [A * np.sin(2 * np.pi * x), A * np.sign(np.sin(2 * np.pi * x) + 1e-12), A * (1 - 4 * np.abs(x - 0.5))][shape]
rms = np.sqrt(np.mean(v))
exact = 0
print(rms, exact)
```

```python solution
import numpy as np
T = 1e-3
t = np.linspace(0, T, n + 1)
x = t / T
v = [A * np.sin(2 * np.pi * x), A * np.sign(np.sin(2 * np.pi * x) + 1e-12), A * (1 - 4 * np.abs(x - 0.5))][shape]
h = t[1] - t[0]
y = v**2
integral = h * (y[0] / 2 + y[1:-1].sum() + y[-1] / 2)
rms = np.sqrt(integral / T)
exact = [A / np.sqrt(2), A, A / np.sqrt(3)][shape]
print(rms, exact)
```

```python tests
import numpy as np
T = 1e-3
tt = np.linspace(0, T, n + 1)
xx = tt / T
vv = [A * np.sin(2 * np.pi * xx), A * np.sign(np.sin(2 * np.pi * xx) + 1e-12), A * (1 - 4 * np.abs(xx - 0.5))][shape]
hh = tt[1] - tt[0]
yy = vv**2
want = np.sqrt(hh * (yy[0] / 2 + yy[1:-1].sum() + yy[-1] / 2) / T)
assert abs(rms - want) < 1e-12 * A, "Square v, integrate with the trapezoid rule (half weight on the two end points), divide by T, take the square root."
assert abs(exact - [A / np.sqrt(2), A, A / np.sqrt(3)][shape]) < 1e-12, "exact is A/√2 for the sine, A for the square wave, A/√3 for the triangle."
assert abs(rms - exact) < 0.02 * A, "Your rms should land close to the exact value."
```

::: right
Right. For a periodic waveform sampled over a whole period, the trapezoid rule is remarkably accurate: the end corrections match and the errors cancel. The square wave's sharp edges are the hardest case.
:::
:::

::: check
given: e0 = 2 | 4 | 8; m = 10 | 5 | 2
answer: e0*1e-6/m^2
tolerance: 1%

## A central difference with step $h$ has an error of {e0} × 10⁻⁶. Its error goes as $h^2$ while rounding is negligible. What should the error be with the step {m} times smaller?

::: right
Right. Dividing $h$ by {m} divides $h^2$, and so the error, by {m}²: {answer}.
:::

::: misses
- [e0*1e-6/m] That scales the error with $h$, like a forward difference. A central difference's error goes as $h^2$.
- [e0*1e-6/m^4] That's fourth order, like Simpson's rule. A central difference is second order.
- [e0*1e-6*m^2] A smaller step makes the error smaller, until rounding takes over.
- [any] Not yet. Divide the error by the square of the factor {m}.
:::
:::

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

::: model
A difference formula has two kinds of error. The truncation error, from replacing the curve with a straight line or a parabola over the step, shrinks as the step shrinks. But the formula subtracts two nearly equal values of the function, each stored with a tiny rounding error, and then divides by the step. As the step shrinks, the difference gets smaller while the rounding errors don't, so their relative effect grows like 1/h. Below some step size the growing rounding error outweighs the shrinking truncation error.
:::
:::

::: practice

::: check
kind: python
given: f = 50 | 1000; A = 1 | 5

## Sample $v = A\sin(2\pi f t)$ (`A` = {A}, `f` = {f} Hz) at 1000 points over one period, and set `dv` to `np.gradient(v, t)`, its derivative. Set `peak` to the largest value of `dv`.

```python starter
import numpy as np
t = np.linspace(0, 1 / f, 1000)
v = A * np.sin(2 * np.pi * f * t)
dv = v
peak = 0
print(peak)
```

```python solution
import numpy as np
t = np.linspace(0, 1 / f, 1000)
v = A * np.sin(2 * np.pi * f * t)
dv = np.gradient(v, t)
peak = dv.max()
print(peak)
```

```python tests
import numpy as np
assert abs(peak - A * 2 * np.pi * f) < 1e-3 * A * 2 * np.pi * f, "peak should be close to A·2πf, the largest slope of the sine."
```
:::

::: check
kind: python
given: n = 10 | 20 | 50 | 100 | 200

## Integrate $t^2$ from 0 to 1 with the trapezoid rule on `n` = {n} steps; set `T` to the result.

```python starter
import numpy as np
T = 0
print(T)
```

```python solution
import numpy as np
t = np.linspace(0, 1, n + 1)
y = t**2
T = (t[1] - t[0]) * (y.sum() - (y[0] + y[-1]) / 2)
print(T)
```

```python tests
assert abs(T - (1 / 3 + 1 / (6 * n**2))) < 1e-12, "The trapezoid rule on t² gives 1/3 + 1/(6n²): h times the sum, with the ends counted half."
```
:::
:::
