---
title: Measurement lab
heading: Statistics, uncertainty and RMS in Python
eyebrow: C11 · Lesson 27 · Measurement lab
xp: 50
---

::: hook
Modern measurements end up as lists of numbers, from a data logger, a scope's memory or a script that steps an instrument through settings. Turning those numbers into results with honest uncertainties is a few lines of code, and writing them yourself makes clear what the instrument's built-in "mean", "std dev" and "RMS" readouts actually compute. In this lab you'll write three: the mean and its standard error, uncertainty propagation through any formula, and the true RMS and crest factor of a sampled waveform.
:::

::: play
- A pulse train of height A and duty cycle D, sampled. The readouts are what your `rms_and_crest` will return: the true RMS, $A\sqrt D$, and the crest factor, $1/\sqrt D$.
- Shrink the duty cycle: the RMS falls slowly while the crest factor climbs. A meter rated for a crest factor of 3 misreads pulses below about 11% duty.
- The dashed line is the RMS level: the DC voltage that would heat a resistor equally.
:::
:::

```sim plot
view: graph
x: t = 0..5 ms
y: v = -0.5..6 V
slider: A = 1..5 = 5 step 0.5 V
slider: D = 0.02..1 = 0.1 step 0.01
plot: A*step(D - (t - floor(t))) | samples: 4000 | label: v(t)
plot: A*sqrt(D) | dashed | label: RMS
readout: true RMS = A*sqrt(D) V
readout: crest factor = 1/sqrt(D) | digits: 3
```

::: predict
## Four readings are 1, 2, 3 and 4 V. What is the standard error of their mean?

- [ ] 1.29 V
- [x] 0.65 V
- [ ] 0.32 V
- [ ] 2.5 V

::: reveal
The sample standard deviation (dividing by N − 1 = 3) is 1.29 V, and the standard error is $1.29/\sqrt4 = 0.65$ V. Dividing by N instead of N − 1 would understate the spread of so few readings.
:::
:::

::: nameit
## Mean and standard error

For N readings, the mean is $\bar x = \sum x_i/N$, the **sample standard deviation** is

$$s = \sqrt{\frac{\sum(x_i - \bar x)^2}{N - 1}}$$

(N − 1 because the mean itself was estimated from the data), and the standard error of the mean is $s/\sqrt N$.

## Propagation by computer

For a result $f(x_1, \ldots, x_n)$ with independent uncertainties $\sigma_i$, the quadrature rule of lesson 2 needs the partial derivatives. A program can estimate each one numerically with a central difference,

$$\frac{\partial f}{\partial x_i} \approx \frac{f(\ldots, x_i + h, \ldots) - f(\ldots, x_i - h, \ldots)}{2h}$$

with a small step h scaled to $x_i$, and then combine $\sqrt{\sum(\partial f/\partial x_i \cdot \sigma_i)^2}$. It works for any formula, however messy.

## True RMS and crest factor

For samples $v_k$, the RMS is $\sqrt{\sum v_k^2/N}$ over a whole number of periods, and the crest factor is the largest |v| over the RMS. That's exactly what a true-RMS meter or a scope's RMS measurement computes.
:::

::: example
## A resistance is found as V/I with V = 5.00 ± 0.02 V and I = 2.000 ± 0.010 mA. What does numerical propagation give?

::: solution
1. **Sensitivity to V.**
   $$\begin{aligned} \frac{\partial R}{\partial V} &= \frac1I \\ &= 500\ \Omega/\text{V} \end{aligned}$$
2. **Sensitivity to I.**
   $$\begin{aligned} \frac{\partial R}{\partial I} &= -\frac{V}{I^2} \\ &= -1.25 \times 10^6\ \Omega/\text{A} \end{aligned}$$
3. **Combine in quadrature.**
   $$\begin{aligned} u_R^2 &= (500 \times 0.02)^2 \\ &\quad + (1.25 \times 10^6 \times 10^{-5})^2 \end{aligned}$$
   so
   $$\begin{aligned} u_R &= \sqrt{100 + 156}\ \Omega \\ &= 16\ \Omega \end{aligned}$$
4. **Compare with lesson 2.** That's 16 Ω on 2500 Ω, matching lesson 2's 0.64%.

**Answer:** R = 2500 ± 16 Ω.
:::
:::

::: example
## Samples of a 5 V pulse train with 10% duty: what are the RMS and crest factor?

::: solution
1. **RMS.**
   $$\begin{aligned} V_\text{rms} &= \sqrt{0.1 \times 25}\ \text{V} \\ &= 1.58\ \text{V} \end{aligned}$$
2. **Crest factor.**
   $$\begin{aligned} \text{CF} &= \frac{5}{1.58} \\ &= 3.16 \end{aligned}$$

**Answer:** 1.58 V RMS, and a crest factor of 3.16.
:::
:::

::: check
given: s = 0.2 | 1 | 3; N = 5 | 20 | 100
answer: s/sqrt(N)
tolerance: 0.5%

## A set of {N} readings has a sample standard deviation of {s}. What is the standard error of their mean?

::: right
Right. $s/\sqrt N$ = {answer}.
:::

::: misses
- [s/N] It falls as $\sqrt N$.
- [any] Not yet. $s/\sqrt N$.
:::
:::

::: check
given: D = 0.04 | 0.25 | 0.5; A = 2 | 10
answer: A*sqrt(D)
unit: V
tolerance: 0.5%

## What is the RMS of a pulse train of height {A} V and duty cycle {D}?

::: right
Right. $A\sqrt D$ = {answer} V.
:::

::: misses
- [A*D] That's the average; RMS squares first, so it's $A\sqrt D$.
- [any] Not yet. $A\sqrt D$.
:::
:::

::: check
kind: python

## Write `mean_and_error(xs)`: return the mean of the list xs and its standard error, using the sample standard deviation (divide by N − 1).

```python starter
def mean_and_error(xs):
    m = sum(xs) / len(xs)
    return m, 0.0
```

```python solution
import math

def mean_and_error(xs):
    n = len(xs)
    m = sum(xs) / n
    s = math.sqrt(sum((x - m) ** 2 for x in xs) / (n - 1))
    return m, s / math.sqrt(n)
```

```python tests
import math, random
m, e = mean_and_error([1, 2, 3, 4])
assert abs(m - 2.5) < 1e-12 and abs(e - 0.6454972) < 1e-6, f"For [1, 2, 3, 4] the mean is 2.5 and the standard error 0.6455; got {m}, {e}."
random.seed(3)
xs = [10 + random.gauss(0, 0.5) for _ in range(400)]
m, e = mean_and_error(xs)
assert abs(e - 0.025) < 0.003, f"400 readings with sigma 0.5 should give a standard error near 0.025; got {e:.4f}."
assert abs(m - 10) < 4 * e, "The mean should be within a few standard errors of the true 10."
```

::: right
Right. The N − 1 matters most for small samples, where it's most often forgotten.
:::
:::

::: check
kind: python

## Write `propagate(f, x, sx)`: f is a function of len(x) arguments, x the measured values and sx their standard uncertainties. Return the propagated uncertainty of f, using central-difference derivatives and quadrature.

```python starter
def propagate(f, x, sx):
    return sum(sx)
```

```python solution
import math

def propagate(f, x, sx, h=1e-6):
    total = 0.0
    for i in range(len(x)):
        step = h * max(abs(x[i]), 1.0)
        up = list(x); dn = list(x)
        up[i] += step; dn[i] -= step
        d = (f(*up) - f(*dn)) / (2 * step)
        total += (d * sx[i]) ** 2
    return math.sqrt(total)
```

```python tests
import math
got = propagate(lambda V, I: V / I, [5.0, 0.002], [0.02, 0.00001])
assert abs(got - 2500 * math.hypot(0.004, 0.005)) < 0.01, f"R = V/I: relative errors 0.4% and 0.5% in quadrature on 2500 ohms is 16.0 ohms; got {got:.3f}."
got = propagate(lambda V, R: V * V / R, [10.0, 100.0], [0.1, 2.0])
assert abs(got - math.hypot(0.02, 0.02)) < 1e-6, f"P = V^2/R with 1% and 2%: 2.83% of 1 W; got {got:.5f}."
got = propagate(lambda a, b: a - b, [7.0, 3.0], [0.3, 0.4])
assert abs(got - 0.5) < 1e-6, f"A difference with 0.3 and 0.4 in quadrature is 0.5; got {got}."
```

::: right
Right. Any formula, any number of inputs, with no hand derivatives.
:::
:::

::: check
kind: python

## Write `rms_and_crest(v)`: return the true RMS of the samples v and the crest factor (largest |v| over the RMS).

```python starter
def rms_and_crest(v):
    avg = sum(abs(x) for x in v) / len(v)
    return avg, 1.0
```

```python solution
import math

def rms_and_crest(v):
    rms = math.sqrt(sum(x * x for x in v) / len(v))
    return rms, max(abs(x) for x in v) / rms
```

```python tests
import math
N = 10000
sq = [1 if (i // 50) % 2 == 0 else -1 for i in range(N)]
r, c = rms_and_crest(sq)
assert abs(r - 1) < 1e-9 and abs(c - 1) < 1e-9, f"A ±1 square wave has RMS 1 and crest factor 1; got {r}, {c}."
tri = [1 - 4 * abs((i / 200) % 1 - 0.5) for i in range(N)]
r, c = rms_and_crest(tri)
assert abs(r - 1 / math.sqrt(3)) < 1e-3, f"A triangle of amplitude 1 has RMS 1/sqrt(3) = 0.577; got {r:.4f}."
pulse = [5 if i % 100 < 10 else 0 for i in range(N)]
r, c = rms_and_crest(pulse)
assert abs(r - 5 * math.sqrt(0.1)) < 1e-9 and abs(c - 1 / math.sqrt(0.1)) < 1e-9, f"5 V pulses at 10% duty: RMS 1.581, crest factor 3.162; got {r:.4f}, {c:.4f}."
```

::: right
Right. That's what the meter's "true RMS" label promises.
:::
:::

::: explain
## Why does the sample standard deviation divide by N − 1 instead of N?

::: model
The deviations are measured from the sample's own mean, which is pulled toward the samples themselves: the sum of squared deviations from the sample mean is always a little smaller than from the true mean. Dividing by N would therefore underestimate the true spread, noticeably so for small samples. One degree of freedom has been used up estimating the mean, leaving N − 1 independent deviations, and dividing by N − 1 corrects the bias exactly on average.
:::
:::

::: practice

::: check
given: s = 0.5 | 2; N = 16 | 64
answer: s/sqrt(N)
tolerance: 0.5%

## Standard error with s = {s} over {N} readings?

::: misses
- [any] $s/\sqrt N$.
:::
:::

::: check
given: A = 3 | 12; D = 0.1 | 0.36
answer: 1/sqrt(D)
tolerance: 0.5%

## Crest factor of {A} V pulses at {D} duty?

::: misses
- [any] $1/\sqrt D$.
:::
:::

::: check
given: a = 1 | 4; b = 2 | 3
answer: sqrt((a*0.1)^2 + (b*0.1)^2)
tolerance: 0.5%

## Uncertainty of x + y with σ = 10% of {a} and 10% of {b}?

::: misses
- [any] Quadrature of 0.1·{a} and 0.1·{b}.
:::
:::
:::
