---
title: "Lab: integrating data"
heading: Energy, charge and RMS from a list of samples
eyebrow: A5 · Lesson 47 · Lab: integrating data
xp: 60
---

::: hook
A power meter doesn't know the formula for the power it's measuring; it has a list of samples. Charge from a current log, energy from a power log and RMS from a voltage record are all integrals of data. In this lab you'll write the trapezoid and Simpson rules for sampled data, handle samples that aren't evenly spaced, let the computer decide how many slices it needs, and measure an RMS from one period of a distorted wave.
:::

::: play
- A clipped sine wave, $v = \max(-A_c, \min(A_c, \sin\theta))$, over one period. Clipping flattens its tops at $\pm A_c$.
- Lower the clip level. The readout is its RMS, computed by integrating $v^2$ exactly; the sine's own RMS is 0.707.
- How much does clipping at 0.9 lower the RMS? At 0.5?
:::

```sim plot
view: graph
x: t = 0..6.2832
y: v = -1.1..1.1
slider: Ac = 0.1..1 = 0.8
plot: sin(t) | dashed | color: ch2 | label: sine
plot: sign(sin(t))*(abs(sin(t)) + Ac - abs(abs(sin(t)) - Ac))/2 | samples: 600 | label: clipped
readout: RMS of the clipped wave = sqrt((2/pi)*(asin(Ac)/2 - Ac*sqrt(1 - Ac^2)/2 + Ac^2*(pi/2 - asin(Ac)))) | digits: 4
```

::: predict
## A current is logged at uneven times: 0, 0.1, 0.3 and 0.6 s. Can the trapezoid rule still find the charge?

- [x] Yes: each trapezoid just uses its own width
- [ ] No: it needs equal spacing
- [ ] Only if the samples are first resampled onto a regular grid
- [ ] Only Simpson's rule can handle it

::: reveal
Yes. Each trapezoid is $\frac{(y_k + y_{k+1})}{2}(x_{k+1} - x_k)$, whatever its width. Simpson's rule, in its usual form, needs equal pairs of slices; the trapezoid rule works on any grid, which is why it's the default for logged data.
:::
:::

::: nameit
## Rules for samples

For samples $y_0, \ldots, y_n$ spaced $h$ apart:
- **trapezoid:** $h\left(\tfrac12y_0 + y_1 + \cdots + y_{n-1} + \tfrac12y_n\right)$;
- **Simpson** ($n$ even): $\frac h3(y_0 + 4y_1 + 2y_2 + \cdots + 4y_{n-1} + y_n)$.

For uneven spacing, add the trapezoids one at a time: $\sum \frac{y_k + y_{k+1}}{2}(x_{k+1} - x_k)$.

## Letting the computer choose $n$

When you can evaluate the function anywhere, start with a few slices and double $n$ until two successive trapezoid results $T_n$ and $T_{2n}$ agree to within a tolerance. Their difference estimates the error, and $\frac{4T_{2n} - T_n}{3}$ (Richardson's correction) is usually far more accurate than either.

## RMS from samples

$V_\text{rms} = \sqrt{\frac{1}{T}\int_0^T v^2\,dt}$: square the samples, integrate over a whole number of periods, divide by the time, take the root. For a clipped sine wave of peak 1 clipped at $A_c$, the exact mean square is $\frac{2}{\pi}\left(\frac{\theta_c}{2} - \frac{A_c\sqrt{1 - A_c^2}}{2} + A_c^2\left(\frac\pi2 - \theta_c\right)\right)$ with $\theta_c = \sin^{-1}A_c$, a handy check.
:::

::: example
## A current is logged as 0 A at 0 s, 2 A at 0.1 s, 3 A at 0.3 s and 1 A at 0.6 s. How much charge passed?

::: solution
1. **Widths.** The slices are 0.1 s, 0.2 s and 0.3 s wide.
2. **Add the trapezoids with their own widths.**
   $$\begin{aligned} q &= \frac{0 + 2}{2}(0.1) + \frac{2 + 3}{2}(0.2) \\ &\quad + \frac{3 + 1}{2}(0.3) \\ &= 0.1 + 0.5 + 0.6 \\ &= 1.2\ \text{C} \end{aligned}$$

**Answer:** 1.2 C passed.
:::
:::

::: example
## Integrate $e^{-x^2}$ on $[0, 1]$ by doubling $n$ until two trapezoid results agree to $10^{-6}$.

::: solution
1. **Double $n$.**
   $$\begin{aligned} T_1 &= 0.683\,940 \\ T_2 &= 0.731\,370 \\ T_4 &= 0.742\,984 \\ T_8 &= 0.745\,866 \end{aligned}$$
   and so on; the differences shrink by about 4 each time.
2. **Stop when two agree.** They first agree to $10^{-6}$ at $n = 512$ against 256, with $T_{512} = 0.746\,824$.
3. **Compare with Richardson's correction.** From $T_8$ and $T_4$ alone it already gives 0.746 826: a tiny fraction of the work for the same accuracy.

**Answer:** the results first agree to $10^{-6}$ at $n = 512$, giving 0.746 824.
:::
:::

::: check
given: y1 = 2 | 3; y2 = 3 | 5; h1 = 0.1 | 0.2; h2 = 0.3 | 0.5
answer: (0 + y1)/2*h1 + (y1 + y2)/2*h2
unit: C
tolerance: 0.5%

## A current reads 0 A, then {y1} A after {h1} s, then {y2} A after a further {h2} s. What charge passed?

::: right
Right. Two trapezoids of different widths: {answer}.
:::

::: misses
- [(0 + 2*y1 + y2)/2*(h1 + h2)/2] That treats the spacing as even. Use each slice's own width.
- [any] Not yet. Add $\frac{y_k + y_{k+1}}{2}\Delta t_k$ for each slice.
:::
:::

::: check
given: Ac = 0.5 | 0.7 | 0.9
answer: sqrt((2/pi)*(asin(Ac)/2 - Ac*sqrt(1 - Ac^2)/2 + Ac^2*(pi/2 - asin(Ac))))
tolerance: 0.5%

## A unit sine wave is clipped at $\pm$ {Ac}. What is its RMS?

::: right
Right. From the exact mean square: {answer}.
:::

::: misses
- [Ac/sqrt(2)] That's a sine of amplitude {Ac}. The clipped wave spends more time near its peak.
- [1/sqrt(2)] That's the unclipped sine.
- [any] Not yet. Use the mean square formula above with $\theta_c = \sin^{-1}A_c$.
:::
:::

::: check
kind: python

## Write `trap(y, h)` and `simpson(y, h)` for equally spaced samples (Simpson needs an even number of slices, so an odd number of samples). Test them on samples of $\sin$ over $[0, \pi]$, whose integral is 2.

```python starter
import math

def trap(y, h):
    return sum(y) * h

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

n = 8
h = math.pi / n
y = [math.sin(k * h) for k in range(n + 1)]
print(trap(y, h), simpson(y, h))
```

```python solution
import math

def trap(y, h):
    return h * (sum(y) - (y[0] + y[-1]) / 2)

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

n = 8
h = math.pi / n
y = [math.sin(k * h) for k in range(n + 1)]
print(trap(y, h), simpson(y, h))
```

```python tests
import math
for n in (4, 8, 16):
    h = math.pi / n
    y = [math.sin(k * h) for k in range(n + 1)]
    et, es = abs(trap(y, h) - 2), abs(simpson(y, h) - 2)
    assert es < et / 20, f"With n = {n}, Simpson should beat the trapezoid rule; got {et:.2e} and {es:.2e}."
assert abs(trap([0, 1, 4, 9], 1) - 9.5) < 1e-12, "trap([0, 1, 4, 9], 1) should be 9.5."
assert abs(simpson([0, 1, 4], 1) - 8 / 3) < 1e-12, "Simpson is exact for x^2: samples 0, 1, 4 with h = 1 give 8/3, the integral of x^2 on [0, 2]."
```

::: right
Right. Slicing the list with steps of 2 picks out the weights 4 and 2 without a loop.
:::
:::

::: check
kind: python
given: k = 0 | 1 | 2

## Write `trap_xy(x, y)` for samples at uneven times. Set `Q` to the charge in the starter's current log number `k` = {k}.

```python starter
logs = [
    ([0, 0.1, 0.3, 0.6], [0, 2, 3, 1]),
    ([0, 0.05, 0.1, 0.4, 0.5, 1.0], [1, 1.5, 2.2, 2.0, 1.1, 0.2]),
    ([0, 1, 1.5, 3, 7], [0, 0.3, 0.35, 0.2, 0]),
]

def trap_xy(x, y):
    return 0

Q = trap_xy(*logs[k])
print(Q)
```

```python solution
logs = [
    ([0, 0.1, 0.3, 0.6], [0, 2, 3, 1]),
    ([0, 0.05, 0.1, 0.4, 0.5, 1.0], [1, 1.5, 2.2, 2.0, 1.1, 0.2]),
    ([0, 1, 1.5, 3, 7], [0, 0.3, 0.35, 0.2, 0]),
]

def trap_xy(x, y):
    return sum((y[i] + y[i + 1]) / 2 * (x[i + 1] - x[i]) for i in range(len(x) - 1))

Q = trap_xy(*logs[k])
print(Q)
```

```python tests
assert abs(trap_xy([0, 0.1, 0.3, 0.6], [0, 2, 3, 1]) - 1.2) < 1e-12, "The first log holds 1.2 C."
assert abs(trap_xy([0, 2], [3, 3]) - 6) < 1e-12, "A constant 3 A for 2 s is 6 C."
x, y = logs[k]
want = sum((y[i] + y[i + 1]) / 2 * (x[i + 1] - x[i]) for i in range(len(x) - 1))
assert abs(Q - want) < 1e-12, f"Log {k} holds {want:.4f} C; got {Q}."
```

::: right
Right. Each trapezoid carries its own width, so gaps in the log cost accuracy but never break the sum.
:::
:::

::: check
kind: python
given: tol = 0.001 | 0.0001 | 0.00001 | 0.000001 | 0.0000001

## Write `auto_trap(f, a, b, tol)`: start with 1 slice, double the number of slices until two successive trapezoid results differ by less than `tol`, and return `(estimate, n)`, where the estimate is the Richardson value $\frac{4T_{2n} - T_n}{3}$ and `n` the larger slice count. Set `r = auto_trap(lambda x: math.exp(-x*x), 0, 1, tol)`.

```python starter
import math

def auto_trap(f, a, b, tol):
    return 0, 1

r = auto_trap(lambda x: math.exp(-x*x), 0, 1, tol)
print(r)
```

```python solution
import math

def trap_f(f, a, b, n):
    h = (b - a) / n
    return h * (f(a) / 2 + sum(f(a + k * h) for k in range(1, n)) + f(b) / 2)

def auto_trap(f, a, b, tol):
    n = 1
    t_old = trap_f(f, a, b, n)
    while True:
        n *= 2
        t_new = trap_f(f, a, b, n)
        if abs(t_new - t_old) < tol:
            return (4 * t_new - t_old) / 3, n
        t_old = t_new

r = auto_trap(lambda x: math.exp(-x*x), 0, 1, tol)
print(r)
```

```python tests
import math
est, n = r
assert abs(est - 0.7468241328) < tol / 10, f"The integral is 0.7468241; got {est}."
expect = {1e-3: 16, 1e-4: 64, 1e-5: 256, 1e-6: 512, 1e-7: 2048}[tol]
assert n == expect, f"With tol {tol} the doubling should stop at n = {expect}; got {n}."
est2, n2 = auto_trap(lambda x: 3 * x * x, 0, 2, 1e-8)
assert abs(est2 - 8) < 1e-9, "The integral of 3x^2 on [0, 2] is 8."
```

::: right
Right. The difference between successive results is a free error estimate, and Richardson's correction uses it to jump far closer to the answer.
:::
:::

::: check
kind: python
given: Ac = 0.5 | 0.7 | 0.9

## Sample one period of a unit sine clipped at $\pm$`Ac` = {Ac} with 2001 points, and set `rms` to its RMS using Simpson's rule on $v^2$. Set `exact` from the mean-square formula in the reading.

```python starter
import math

rms = 0
exact = 0
print(rms, exact)
```

```python solution
import math

n = 2000
h = 2 * math.pi / n
v = [max(-Ac, min(Ac, math.sin(k * h))) for k in range(n + 1)]
sq = [x * x for x in v]
integral = h / 3 * (sq[0] + sq[-1] + 4 * sum(sq[1:-1:2]) + 2 * sum(sq[2:-1:2]))
rms = math.sqrt(integral / (2 * math.pi))
tc = math.asin(Ac)
exact = math.sqrt(2 / math.pi * (tc / 2 - Ac * math.sqrt(1 - Ac**2) / 2 + Ac**2 * (math.pi / 2 - tc)))
print(rms, exact)
```

```python tests
import math
tc = math.asin(Ac)
want = math.sqrt(2 / math.pi * (tc / 2 - Ac * math.sqrt(1 - Ac**2) / 2 + Ac**2 * (math.pi / 2 - tc)))
assert abs(exact - want) < 1e-12, "exact should come from the mean-square formula."
assert abs(rms - want) < 1e-5, f"Simpson's rule on 2000 slices should match the exact RMS {want:.6f}; got {rms}."
assert rms < 1 / math.sqrt(2), "Clipping lowers the RMS below the sine's 0.7071."
```

::: right
Right. The kinks where the clipping starts cost Simpson's rule some of its accuracy, but 2000 slices still land within $10^{-5}$.
:::
:::

::: check
kind: python

## Write `romberg(f, a, b, m)`: build a triangle of estimates. Row $i$ starts with the trapezoid rule on $2^i$ slices; each next entry is $R_{i,j} = R_{i,j-1} + \frac{R_{i,j-1} - R_{i-1,j-1}}{4^j - 1}$. Return the last entry of row $m - 1$. Set `r = romberg(lambda x: math.exp(-x*x), 0, 1, 5)`.

```python starter
import math

def romberg(f, a, b, m):
    return 0

r = romberg(lambda x: math.exp(-x*x), 0, 1, 5)
print(r)
```

```python solution
import math

def trap(f, a, b, n):
    h = (b - a) / n
    return h * ((f(a) + f(b)) / 2 + sum(f(a + k * h) for k in range(1, n)))

def romberg(f, a, b, m):
    rows = [[trap(f, a, b, 1)]]
    for i in range(1, m):
        row = [trap(f, a, b, 2**i)]
        for j in range(1, i + 1):
            row.append(row[j - 1] + (row[j - 1] - rows[i - 1][j - 1]) / (4**j - 1))
        rows.append(row)
    return rows[-1][-1]

r = romberg(lambda x: math.exp(-x*x), 0, 1, 5)
print(r)
```

```python tests
import math
assert abs(r - 0.7468241328124271) < 1e-9, f"Five rows of Romberg should land within 1e-9 of 0.746824133; got {r}."
assert abs(romberg(math.sin, 0, math.pi, 6) - 2) < 1e-10, "The integral of sin over [0, pi] is 2."
assert abs(romberg(lambda x: x**3, 0, 2, 2) - 4) < 1e-12, "Two rows already give Simpson's rule, exact for cubics."
```

::: right
Right. Sixteen trapezoid slices, combined this way, beat thousands of plain ones.
:::
:::

::: explain
## Why is the trapezoid rule the default for logged data, even though Simpson's rule is more accurate for smooth functions?

::: model
Simpson's rule gets its accuracy by fitting a parabola through each pair of equal slices, which needs evenly spaced samples, an even number of slices, and a function smooth enough that a parabola describes it. Logged data often fails all three: loggers skip or bunch samples, records end at an odd count, and real signals have kinks, switching edges and noise. The trapezoid rule needs none of that: each slice uses only its own two points and its own width, so it works on any spacing, and its error behaves sensibly at kinks. With noisy data, the accuracy is usually limited by the noise and the sampling rate, not by the rule, so the trapezoid rule's simplicity costs little.
:::
:::

::: practice

::: check
given: y1 = 0.1..10; y2 = 0.1..10; h1 = 0.01..1; h2 = 0.01..1
answer: y1/2*h1 + (y1 + y2)/2*h2
tolerance: 0.5%

## Trapezoids: 0, {y1}, {y2} with widths {h1} and {h2}?

::: misses
- [any] Add $\frac{y_k + y_{k+1}}{2}\Delta t_k$.
:::
:::

::: check
given: Ac = 0.1..0.99
answer: sqrt((2/pi)*(asin(Ac)/2 - Ac*sqrt(1 - Ac^2)/2 + Ac^2*(pi/2 - asin(Ac))))
tolerance: 0.5%

## RMS of a unit sine clipped at {Ac}?

::: misses
- [any] Use the clipped mean-square formula.
:::
:::
:::
