---
title: Uncertainty lab
heading: Budgets, Monte Carlo propagation and pass-fail decisions in Python
eyebrow: C11 · Lesson 7 · Uncertainty lab
xp: 50
---

::: hook
Lessons 1 to 3 built uncertainty by hand: standard uncertainties, propagation by derivatives, budgets and guard bands. Code makes all of it routine, and adds a method that needs no derivatives at all: simulate the measurement thousands of times with random inputs and look at the spread of the results. In this lab you'll convert specifications to standard uncertainties, combine a budget, propagate by Monte Carlo, and write the decision rule that turns a reading and its uncertainty into pass, fail or indeterminate.
:::

::: play
- The curve is a budget's combined uncertainty as one contribution x grows while the other, $u_1$, stays fixed: $\sqrt{u_1^2 + x^2}$.
- While x is less than a third of $u_1$, it barely matters: the total rises less than 6%. Once x passes $u_1$, it takes over.
- This is why budgets are read from the top: improving anything but the largest term changes almost nothing.
:::

```sim plot
view: graph
x: x = 0..3
y: u = 0..3.5
slider: u1 = 0.2..2 step 0.05 = 1
plot: sqrt(u1^2 + x^2) | label: combined
plot: u1 + 0*x | dashed | label: the larger term alone
readout: combined when x is a third of u1 = sqrt(u1^2 + (u1/3)^2) | digits: 3
```

::: predict
## A Monte Carlo propagation of $y = x^2$ uses x drawn from a Gaussian with mean 0 and σ = 1. What spread does y have, and what does first-order propagation by derivatives predict?

- [ ] Both give 0
- [x] Monte Carlo gives about 1.41; derivatives give 0
- [ ] Both give 1.41
- [ ] Monte Carlo gives 0; derivatives give 2

::: reveal
Monte Carlo gives $\sqrt2 = 1.41$ (y is chi-square distributed with mean 1). The derivative of $x^2$ at x = 0 is zero, so first-order propagation predicts no uncertainty at all. Linearization fails when a function is curved over the range of its inputs; simulation doesn't care.
:::
:::

::: nameit
## The pieces

- **Standard uncertainties**: rectangular ±a gives $a/\sqrt3$, triangular ±a gives $a/\sqrt6$, and an expanded uncertainty U quoted at k = 2 gives U/2.
- **A budget**: $u_c = \sqrt{\sum(c_iu_i)^2}$ and $U = ku_c$.
- **Monte Carlo propagation**: draw each input from its distribution, compute the result, repeat N times, and take the mean and standard deviation of the results. Seed the random generator so the answer is reproducible. The precision of the estimated spread improves as $1/\sqrt N$, so tens of thousands of trials give two or three good digits.
- **Decision rules**: with expanded uncertainty U and limits L and H, a reading x is a clear **pass** inside $[L + U, H - U]$, a clear **fail** outside $[L - U, H + U]$, and **indeterminate** in between.
:::

::: example
## Propagate R = V/I by Monte Carlo with V = 5.00 ± 0.02 V and I = 2.000 ± 0.010 mA (standard uncertainties), and compare with the derivative formula.

::: solution
1. **Monte Carlo.** Twenty thousand trials give R = 2500 Ω with a spread of 15.9 Ω.
2. **Derivative formula.**
   $$\begin{aligned} u_R &= 2500\ \Omega \\ &\quad \times \sqrt{(0.02/5)^2 + (0.01/2)^2} \\ &= 16.0\ \Omega \end{aligned}$$
3. **Why they agree.** V/I is nearly linear over such small uncertainties; the simulation would reveal the difference if I's uncertainty were a large fraction of I.

**Answer:** both give R = 2500 Ω, with an uncertainty of 15.9 Ω by Monte Carlo and 16.0 Ω by the formula.
:::
:::

::: example
## A 10 V reference must read between 9 V and 10 V, and U = 0.02 V. Classify readings of 9.97, 9.99 and 10.05 V.

::: solution
1. **Acceptance zone.** Pulling each limit in by U = 0.02 V leaves [9.02, 9.98] V.
2. **9.97 V.** It is inside [9.02, 9.98]: pass.
3. **9.99 V.** It is between 9.98 and 10.02: indeterminate, because the true value could be on either side of the limit.
4. **10.05 V.** It is above 10.02: fail.
5. **An indeterminate reading.** It calls for a better measurement or a decision rule agreed in advance.

**Answer:** 9.97 V passes, 9.99 V is indeterminate, and 10.05 V fails.
:::
:::

::: check
given: u1 = 0.5 | 1 | 2; r = 0.2 | 0.5 | 1
answer: sqrt(u1^2 + (r*u1)^2)
tolerance: 0.5%

## A budget has a term of {u1} and another {r} times as large. What is the combined uncertainty?

::: right
Right: {answer}.
:::

::: misses
- [u1 + r*u1] They add in quadrature, not linearly.
- [any] Not yet. $\sqrt{u_1^2 + (ru_1)^2}$.
:::
:::

::: check
kind: python

## Write `standard_u(a, dist)`: the standard uncertainty for a half-width a when dist is `'rectangular'` or `'triangular'`, or for an expanded uncertainty a at k = 2 when dist is `'normal'`. Then write `budget(rows)`: given a list of `(u, c)` pairs, return `(uc, U)` with k = 2.

```python starter
def standard_u(a, dist):
    return a

def budget(rows):
    return (sum(u for u, c in rows), 0.0)
```

```python solution
import math

def standard_u(a, dist):
    return {'rectangular': a / math.sqrt(3), 'triangular': a / math.sqrt(6), 'normal': a / 2}[dist]

def budget(rows):
    uc = math.sqrt(sum((c * u) ** 2 for u, c in rows))
    return (uc, 2 * uc)
```

```python tests
import math
assert abs(standard_u(0.05, 'rectangular') - 0.028868) < 1e-6, "±0.05 rectangular: 0.0289."
assert abs(standard_u(0.06, 'triangular') - 0.024495) < 1e-6, "±0.06 triangular: 0.0245."
assert abs(standard_u(0.02, 'normal') - 0.01) < 1e-12, "U = 0.02 at k = 2: 0.01."
uc, U = budget([(0.01155, 1), (0.0025, 1), (0.00029, 1), (0.00095, 1)])
assert abs(uc - 0.011859) < 1e-6 and abs(U - 0.023718) < 1e-6, f"The lesson's budget: uc = 0.0119, U = 0.0237; got {uc}, {U}."
uc, U = budget([(0.01, 2), (0.03, 1)])
assert abs(uc - math.sqrt(0.0013)) < 1e-12, "Sensitivity coefficients multiply before squaring."
```

::: right
Right. A budget is a few lines of code once every term is a standard uncertainty.
:::
:::

::: check
kind: python

## Write `monte_carlo(f, means, sds, n, seed)`: draw each input from a Gaussian with the given mean and standard deviation using `random.Random(seed)`, evaluate f n times, and return `(mean, std)` of the results (std with n − 1).

```python starter
def monte_carlo(f, means, sds, n, seed):
    return (f(*means), 0.0)
```

```python solution
import math, random

def monte_carlo(f, means, sds, n, seed):
    rng = random.Random(seed)
    ys = [f(*[rng.gauss(m, s) for m, s in zip(means, sds)]) for _ in range(n)]
    mu = sum(ys) / n
    return (mu, math.sqrt(sum((y - mu) ** 2 for y in ys) / (n - 1)))
```

```python tests
import math
m, s = monte_carlo(lambda x, y: x + y, [1, 2], [0.03, 0.04], 20000, 1)
assert abs(m - 3) < 0.002 and abs(s - 0.05) < 0.002, f"A sum: mean 3, spread √(0.03² + 0.04²) = 0.05; got {m:.4f}, {s:.4f}."
m, s = monte_carlo(lambda v, i: v / i, [5.0, 0.002], [0.02, 0.00001], 20000, 2)
assert abs(m - 2500) < 1 and abs(s - 16.0) < 0.5, f"V/I: about 2500 Ω with a spread near 16 Ω; got {m:.1f}, {s:.2f}."
m, s = monte_carlo(lambda x: x * x, [0.0], [1.0], 50000, 3)
assert abs(s - math.sqrt(2)) < 0.03, f"x² at x = 0: spread √2 = 1.414, which derivatives miss; got {s:.4f}."
```

::: right
Right. The same function propagates through any formula, linear or not.
:::
:::

::: check
kind: python

## Write `decide(x, lo, hi, U)`: return `'pass'` if x is within [lo + U, hi − U], `'fail'` if it's below lo − U or above hi + U, and `'indeterminate'` otherwise.

```python starter
def decide(x, lo, hi, U):
    return 'pass' if lo <= x <= hi else 'fail'
```

```python solution
def decide(x, lo, hi, U):
    if lo + U <= x <= hi - U:
        return 'pass'
    if x < lo - U or x > hi + U:
        return 'fail'
    return 'indeterminate'
```

```python tests
assert decide(9.97, 9, 10, 0.02) == 'pass', "9.97 V is clearly inside."
assert decide(9.99, 9, 10, 0.02) == 'indeterminate', "9.99 V is within U of the upper limit."
assert decide(10.05, 9, 10, 0.02) == 'fail', "10.05 V is clearly outside."
assert decide(8.99, 9, 10, 0.02) == 'indeterminate', "8.99 V is within U of the lower limit."
assert decide(8.9, 9, 10, 0.02) == 'fail', "8.9 V is clearly below."
```

::: right
Right. Saying "indeterminate" is the honest answer when the uncertainty straddles a limit.
:::
:::

::: explain
## When does Monte Carlo propagation give a different answer from propagation with derivatives, and which should be trusted?

::: model
Derivative propagation replaces the function with a straight line through the measured point and assumes the inputs' spreads are small enough that the curvature doesn't matter. When an uncertainty is a sizable fraction of its input, or the function bends sharply (a square near zero, a division by a quantity that could approach zero, a threshold), the straight-line approximation misjudges both the spread and the mean of the result. Monte Carlo makes no such approximation: it pushes real samples through the real function, so it captures curvature, skewed distributions and correlations when they're modeled. When the two methods disagree, the simulation is the one to trust, provided enough trials were run.
:::
:::
