M07 — Averaging and Monte Carlo
Some answers are averages: an integral over many inputs, the mean of an output when the inputs are uncertain, the slope through scattered data. Monte Carlo computes an average by sampling, and its error falls slowly, but at a rate that is the same in one dimension as in a hundred. This notebook measures the rate, puts an honest bar on the answer, cuts the bar with variance reduction, reads a least-squares fit as an average, and ends by sampling an uncertain suspension pivot.
Book pages: Averaging, An average, and its error bar and Fitting, and what
the fit does not say in books/numerical-methods.
The question. In one dimension Monte Carlo's error falls far slower than a quadrature rule's. Why is it the method of choice for integrals in many dimensions, and how do you know how wrong its answer is?
By the end you can:
- derive the standard error of a sample mean and measure its order with a convergence table
- explain why a product quadrature rule's order collapses as the dimension grows and Monte Carlo's does not
- build a confidence interval from the sample variance, and say when its coverage is not what it claims
- use a seed to make one run repeatable, and read two seeds' disagreement
- cut the variance with a control variate or antithetic pairs, and predict the factor
- read a least-squares line as a projection and a weighted average, and relate the slope to
- run a sampled sensitivity study and split an output's spread among its inputs
Assumes: M01's convergence table; mean, variance and covariance; a 2 × 2 linear system.
How to use it: predict before you reveal, commit before you check, and move the controls until the equation's behaviour stops surprising you.
Warm-up: remember
Closed book, from earlier notebooks. Answer before you read on.
1. Monte Carlo integration and its rate
Setting: the problem, its sets and its symbols
Problem. Given the probability space with and uniform, an integrand and i.i.d. samples , find by the sample mean , and find the order such that the RMS error as .
| Symbol | In | Meaning |
|---|---|---|
| the probability space: is area on the unit square | ||
| the density of ; here on | ||
| the quarter disc, of area | ||
| the integrand | ||
| the target , here | ||
| the sample points, | ||
| the sample size, in row of the table | ||
| the estimator , a random variable | ||
| , the variance of one sample | ||
| the RMS error , measured over 64 independent runs | ||
| the observed order , the table's last column | ||
| in the kernel: the generator's state, the fraction of points in , and the point count |
How these symbols connect
The uniform density on turns the area integral of into the expectation , with single-sample variance . Drawing i.i.d. points produces the random estimator ; repeating 64 independent runs yields the RMS error , and successive ratios measure the empirical order . In the Rust kernel, an LCG updates state to count hits out of points.
Symbol-by-symbol notes
$(\Omega, \mathcal{F}, P)$ and $p$
is the probability space: sample space , event -algebra and probability measure . Because is uniform on the unit square of area , its density is on , so equals the ordinary area integral .
$g = 4 \cdot \mathbf{1}_D$ and $\sigma^2$
The indicator equals inside the quarter disc and outside, so takes only the values and . Its variance is a fixed property of a single draw, independent of .
$\hat I\lt em>N$ versus $I$ and $e\lt /em>N$
is a fixed real number (here ), whereas is a random variable whose single-run error fluctuates from seed to seed. The RMS error averages squared errors over 64 independent runs so the scaling with can be read cleanly.
$\alpha$ and the kernel triple $(s, \hat p, n)$
Because each table row quadruples , the observed order uses base so that reads off directly. In the Rust kernel, is an unsigned 32-bit LCG state (not a sample standard deviation), is the hit fraction (so estimates ), and is the point count.
Drop points uniformly in the unit square and count the fraction inside the quarter circle . That fraction estimates the area , so four times it estimates . In general, an integral is an expectation,
with drawn from . Here is uniform on the square and .
A single run's error is random, so the table measures the root-mean-square error over 64 independent runs at each , in M01's convergence table: grows by 4 a row, and the order column is of successive error ratios. Before deriving anything, predict how fast the error falls.
Why. The estimator is unbiased by linearity of expectation. Independence kills the cross terms in its variance:
So the error has order in . For the quarter circle is 4 times a coin with , so . The reveal compares the measured table with this prediction.
Reveal result (lock in your prediction above first)
| N | RMS error | σ/√N | observed order |
|---|---|---|---|
| 100 | 0.1755 | 0.1642 | — |
| 400 | 0.0842 | 0.0821 | 0.5293 |
| 1600 | 0.0435 | 0.0411 | 0.4759 |
| 6400 | 0.0186 | 0.0205 | 0.6119 |
| 25600 | 0.0104 | 0.0103 | 0.4197 |
| 102400 | 0.0049 | 0.0051 | 0.5499 |
Quadrupling halves the error. Here . The order column wanders because each RMS is itself a 64-run estimate; a least-squares slope of error on over all rows gives 0.52. §5 says what that fit is. A random error needs a fit, or many repeats, before its order reads cleanly.
The site's browser kernel is this estimator in Rust. Its generator is a 32-bit linear congruential generator (LCG), , keeping the top 24 bits; each step draws a batch of points and reports and , the binomial form of the estimated standard error.
source: solvers/ot-solve/src/kernels/montecarlo.rs:55-60
fn next(state: &mut u32) -> f64 {
*state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
// The top 24 bits are the ones with the good distribution; the low bits of an
// LCG are the ones with the period.
(*state >> 8) as f64 / 16_777_216.0
}
source: solvers/ot-solve/src/kernels/montecarlo.rs:84-108
pub fn step(a: &mut Arena<'_>) -> Status {
let batch = a.params()[P_BATCH];
if !batch.is_finite() || batch < 1.0 {
return Status::BadParameter;
}
let batch = batch as u32;
let (mut rng, mut n, mut inside) = {
let state = a.state();
(
state[S_RNG] as u32,
state[S_N] as u64,
state[S_INSIDE] as u64,
)
};
for _ in 0..batch {
let x = next(&mut rng);
let y = next(&mut rng);
if x * x + y * y <= 1.0 {
inside += 1;
}
n += 1;
}
let p = inside as f64 / n as f64;
let estimate = 4.0 * p;
let stderr = 4.0 * (p * (1.0 - p) / n as f64).sqrt();
When the $\sigma/\sqrt N$ rate breaks
- Assumes: independent samples from the right distribution, with finite variance
- When it fails: with infinite variance (a heavy tail) the error falls slower than and never settles; with correlated samples the true error is larger than says
- Check: the order column of the convergence table should settle near 0.5, and should stop drifting as grows
2. Dimension: Monte Carlo against a grid as the dimension grows
Setting: the problem, its sets and its symbols
Problem. Given a dimension and an integrand , find from evaluations of , and compare the error of the product midpoint rule with that of the Monte Carlo mean at the same .
| Symbol | In | Meaning |
|---|---|---|
| the dimension (the slider) | ||
| a point of the unit cube | ||
| the target , equal to 1 for every | ||
| evaluations of : for the rule, any for Monte Carlo | ||
| midpoint-rule points per axis | ||
| the product midpoint rule: the mean of over the cell centres | ||
| the Monte Carlo points, | ||
| the Monte Carlo mean | ||
| for uniform on | ||
| the rule's error , and Monte Carlo's RMS error over 16 runs |
How these symbols connect
Choosing the dimension fixes the unit cube and the product integrand , whose exact integral is . On the grid side, placing midpoints along each axis requires evaluations and produces the deterministic rule with error . On the sampling side, i.i.d. uniform draws form , whose per-sample variance is and whose RMS error is measured across 16 runs at the same evaluation budget .
Symbol-by-symbol notes
$f$ and $I_d$
is separable across coordinates. Each one-dimensional factor integrates to on , so in every dimension and the product rule equals the 1-D midpoint rule raised to the power .
$m$ versus $N$
is the number of grid cells per coordinate axis, whereas is the total count of function evaluations. For the product rule they are coupled by , while Monte Carlo accepts any positive integer .
$\sigma_d^2$
is the variance of a single uniform draw on . Unlike , it depends on because the product concentrates more strongly near the centre of the cube as grows.
$E\lt em>{\text{rule}}$ versus $E\lt /em>{\text{MC}}$
is deterministic and computed exactly for each , whereas is estimated as the root-mean-square error of across 16 independent runs at each .
Take on ; each factor integrates to 1, so in every dimension. A product midpoint rule with points per axis uses points. Its error per axis is , so
The rule's order in is : excellent at , equal to Monte Carlo's at , worse beyond. Because is a product, the rule's value is the 1-D rule's value to the power , so its error is computed exactly even at points. The Monte Carlo points are the RMS of 16 independent runs. Move and watch the rule's line flatten while Monte Carlo's keeps its slope.
Reveal result (lock in your prediction above first)
At and : the midpoint rule's error is 0.230, Monte Carlo's standard error is 0.0082, about 28 times smaller.
Fitted orders at : midpoint rule 0.29 (theory ), Monte Carlo 0.49 (theory 0.5). The rate is dimension-free; the constant is not. grows with , which lifts the Monte Carlo line without tilting it.
When Monte Carlo in many dimensions breaks
- Assumes: the integrand's standard deviation stays moderate as grows
- When it fails: a product of many factors can have growing exponentially in : the rate survives but the constant does not, and rare large values dominate
- Check: report from the run itself; if is large against the mean, a better sampler is needed, not more dimensions of grid
3. Error bars, coverage and seeds
Setting: the problem, its sets and its symbols
Problem. Given i.i.d. real samples with unknown mean and variance , find an interval , computed from the samples alone, that aims at ; then measure its actual coverage by repetition. Separately, given a seed , find the run it determines.
| Symbol | In | Meaning |
|---|---|---|
| the samples: standard normal, §1's indicator, or exponential with mean 1 | ||
| their true mean and variance, unknown to the estimator | ||
| the sample mean | ||
| the sample variance, with divisor | ||
| the normal quantile; for a nominal 95% | ||
| , random through the samples | ||
| the estimated standard error ; the seed table uses the binomial form , with the fraction of points in the quarter disc | ||
| the coverage, estimated as the fraction of 4000 repeats whose interval contains | ||
| the generator's state; is the seed and |
How these symbols connect
From i.i.d. samples with unknown mean and variance , the sample mean and sample variance yield the estimated standard error . Combining , and the normal quantile builds the random interval , whose empirical coverage is measured over 4000 repeats. Separately, choosing an initial seed drives the recurrence to generate a reproducible stream of draws and a repeatable estimate with its binomial .
Symbol-by-symbol notes
$s^2$ versus $\sigma^2$
is the fixed, unknown population variance of the distribution, whereas is a random estimate computed from the draws. The divisor accounts for measuring deviations from rather than from the unknown .
$C\lt em>N$ and $P(\mu \in C\lt /em>N)$
The true mean is fixed; the interval is the random object that shifts and changes width on every sample. Coverage is a frequency property of the procedure across independent repeats, estimated here from 4000 trials.
$\mathrm{SE}$: general versus binomial form
For general real samples . In the seed table for the quarter-disc estimator, each draw is a Bernoulli hit scaled by with sample fraction , so the kernel computes .
$\xi\lt em>k$ and the seed $\xi\lt /em>0$
This section denotes the LCG state by rather than §1's so it does not collide with the sample standard deviation . Fixing the integer seed fixes the entire sequence deterministically.
is as unknown as . Replace it with the sample variance, whose pays for measuring deviations from rather than from the true mean:
By the central limit theorem is close to normal for large , so gives a 95% interval: over many repeats, 95% of such intervals contain the true mean. That is a claim about the procedure, and it can be tested.
Seeds. A pseudo-random generator is a deterministic sequence; the seed picks the starting point. The same seed reproduces a run bit for bit, which is what makes a Monte Carlo result checkable. Below, the kernel's generator is transcribed into Python and run for 8000 points (16 steps of 500, the kernel's first test case). Change the seed: the estimate moves, and it moves by about one standard error.
| seed | estimate | standard error | error / SE | rerun identical |
|---|---|---|---|---|
| 1 | 3.1605 | 0.0182 | +1.04 | True |
At seed 1 a compiled copy of the kernel's next and loop gives the same 3.1605 and
0.0182, so the transcription is exact. Report the seed with the result, and the bar
with both.
Reveal result (lock in your prediction above first)
| N | normal | π indicator | exponential |
|---|---|---|---|
| 5 | 0.88 | 0.7 | 0.808 |
| 10 | 0.922 | 0.908 | 0.875 |
| 30 | 0.936 | 0.901 | 0.902 |
| 100 | 0.948 | 0.948 | 0.937 |
| 1000 | 0.95 | 0.948 | 0.955 |
Fraction of 4000 nominal-95% intervals that contain the true mean. At the exponential covers 80.8% and even the normal only 88.0% (for a normal, the shortfall is exactly what Student's corrects). The π indicator covers 70.0%: with probability all five points land inside, , and the bar has zero width. By all three are within sampling noise of 95%.
When the 95% interval breaks
- Assumes: is large enough that is close to normal and close to
- When it fails: at small or with a skewed or heavy-tailed output the coverage falls below 95% (81% for the exponential at in §3)
- Check: run a coverage experiment on a case with a known answer, or compare the bar across seeds
4. Variance reduction
Setting: the problem, its sets and its symbols
Problem. Given uniform on and , find an unbiased estimator of with less variance per evaluation of than plain sampling: find minimising , and compare and the antithetic pair with .
| Symbol | In | Meaning |
|---|---|---|
| one sample, with known mean | ||
| the integrand | ||
| the target | ||
| , the plain estimator's variance per sample | ||
| the control coefficient (the slider) | ||
| the control-variate sample | ||
| the minimiser of | ||
| the correlation | ||
| the antithetic pair , which costs two evaluations |
How these symbols connect
A uniform draw on feeds both the integrand (with target mean and baseline variance ) and the zero-mean control term to form the unbiased estimator . Varying traces down to its minimum at , governed by the correlation , while pairing with defines the antithetic average at twice the evaluation cost per sample.
Symbol-by-symbol notes
$Y_c$ and $c$ versus $c^*$
Because , is unbiased for every , not only at the optimum. The slider sweeps , while marks the unique minimiser of .
$\rho$ and $\sigma_f^2$
is the plain estimator's variance per draw, and is the dimensionless linear correlation between the integrand and the control variate. Both are fixed properties of on .
$Y_A$ and cost per evaluation
One antithetic sample requires two evaluations of rather than one. Comparing fairly against plain sampling or accounts for that factor of two in evaluation budget, not just variance per sample.
The rate is fixed at ; the constant is not. Every halving of saves a factor of four in samples. Take , with uniform on .
Control variate. itself has known mean and tracks . For any , is still unbiased, with
A quadratic in , smallest at , where it equals . So the factor gained is : buys about 5, about 50.
Antithetic pairs. Average and . A pair costs two evaluations and has variance . Because is monotone the covariance is negative, so a pair beats two independent draws.
Move : the sampled variance of traces the parabola.
Reveal result (lock in your prediction above first)
| estimator | variance per sample | per evaluation, against plain |
|---|---|---|
| plain | 0.2420 | 1 |
| control, (sampled) | 0.24452 | 1.0 |
| control, (exact) | 0.00394 | 61.4 |
| antithetic pair (exact; sampled 0.00392) | 0.00391 | 30.9 |
, and . The antithetic factor is per evaluation: a pair costs two. Note what is: , the least-squares slope of on . The control variate subtracts a fitted line, and the residual is what is left to average. §5 is that fit.
When variance reduction breaks
- Assumes: the control is strongly correlated with and its mean is known exactly; for antithetic pairs, is monotone
- When it fails: a weak correlation buys only , near 1; a control with an estimated mean brings that estimate's error with it; a symmetric makes antithetic pairs cost double
- Check: measure the variance per evaluation of both estimators on a pilot run before committing to the long one
5. Regression as averaging
Setting: the problem, its sets and its symbols
Problem. Given data , , find minimising . Then find the reverse fit minimising , and compare the two lines in the same axes.
| Symbol | In | Meaning |
|---|---|---|
| the number of points, here 5 | ||
| the data: , , with on the slider | ||
| the design matrix | ||
| intercept and slope, the unknowns; is the minimiser | ||
| the sum of squared vertical residuals | ||
| the residual | ||
| the means of and | ||
| , and | ||
| the slope from to point , for | ||
| the correlation coefficient | ||
| the standard deviations of and | ||
| the residual standard deviation, , and the slope's standard error | ||
| the reverse fit |
How these symbols connect
The data pairs assemble into the design matrix and response vector ; minimising selects and yields the residual vector . The means and centred sums express the fit through the pairwise slopes , the correlation and the spreads , while gives the residual standard deviation and slope uncertainty . Swapping the roles of and defines the reverse fit from horizontal residuals so both lines can be plotted together.
Symbol-by-symbol notes
$X$, $\beta$ and $\hat\beta$
The design matrix places a column of ones beside , so has entries . Here is any candidate parameter pair and is the minimiser of .
$S\lt em>{xx}, S\lt /em>{yy}, S\lt em>{xy}$ versus $s\lt /em>x, s_y$ and $r$
are unscaled centred sums of squares and cross-products, whereas and divide by before taking the square root. The correlation is dimensionless because any common divisor cancels between numerator and denominator.
$m\lt em>i$ and the point $x\lt /em>i = \bar x$
Each is the slope from the mean point to . It is undefined when (here ), which carries zero weight in the weighted average for .
$s$ versus $s_y$ and $\mathrm{SE}(b)$, and $(a', b')$
is the residual standard deviation (with degrees of freedom for two fitted parameters), not the spread of itself; it sets the slope standard error . The primed pair minimises squared horizontal residuals instead of vertical ones.
The book's five points: and . Fit by minimising . Setting both partial derivatives to zero gives the normal equations, which in matrix form, with , are
Read the left form geometrically: the residual is orthogonal to every column of , so is the orthogonal projection of onto the plane spanned by and . The ones row says , so the line passes through . The row then gives
a weighted average of the slopes from the mean point to each data point, the weights favouring points far from . That is why one distant point can move the line. The correlation coefficient rescales the same sum, so ; and with . Move the last point and watch , and the bar.
Reveal result (lock in your prediction above first)
| quantity | value |
|---|---|
| slope , intercept | 0.5700, 1.4600 |
| weighted average of slopes to the mean point | 0.5700 |
| , and | 0.8314, 0.6913 |
| (slopes of on and on ) | 0.6913 |
| , and | 0.2199, 2.6 |
| 4.4e-15 |
At the scissors about the mean point is open. Slide to the book's and is so close to 1 that the lines almost coincide; the table then shows the page's numbers: , , . is zero to round-off for any data: it checks the arithmetic, never the model. This is the bridge to M03: the normal equations are a linear system, and forming squares the condition number, which is why large fits use QR on instead.
When least squares breaks
- Assumes: the errors are independent with constant variance, and the model is linear in its parameters
- When it fails: correlated or heteroscedastic errors make too small; one high-leverage point can move the slope a long way
- Check: plot the residuals against and in order; checks the arithmetic, never the model
6. A sensitivity study: an uncertain pivot
Setting: the problem, its sets and its symbols
Problem. Given independent errors and in the two inner pivot heights, and the map from those heights to the camber change over mm of travel, find the distribution of (its mean, standard deviation and 95% range) and the share of owed to each input.
| Symbol | In | Meaning |
|---|---|---|
| the input index: the lower arm's inner pivot, the upper arm's | ||
| the pivot heights (m); nominal , | ||
| the errors in the two heights (mm) | ||
| their scatter (mm), the two sliders | ||
| wheel travel (mm) | ||
| the lower arm's angle (rad), found by bisection so that the travel is | ||
| camber (deg) as a function of travel, for one geometry | ||
| the camber change (deg) as a function of ; at the nominal heights | ||
| the sensitivity at the nominal heights (deg/mm) | ||
| the number of sampled geometries, 2000 | ||
| the squared sample correlation of with input : its estimated share of |
How these symbols connect
Independent normal errors (with slider spreads in mm) perturb the nominal inner pivot heights (converted from mm to m). For each of sampled geometries, bisection solves for the lower-arm angle that achieves wheel travel mm, evaluates camber (deg) and forms the camber change . Regressing the sampled outputs on each input estimates its local sensitivity (deg/mm) and variance share .
Symbol-by-symbol notes
$z\lt em>i$ (m) versus $\delta\lt /em>i$ and $\sigma_i$ (mm)
Nominal pivot heights and are in metres for the front-view geometry, while the perturbations and slider spreads are in millimetres. The solver divides by before adding it to , and reports sensitivities in deg/mm.
$s$, $\theta$ and $\gamma(s)$
Wheel travel mm is the target vertical displacement of the wheel centre, not the direct linkage input. For each geometry, bisection finds the lower-arm angle rad that matches mm, and reads the upright camber in degrees.
$y$ versus $y\lt em>0$ and $k\lt /em>i$
is the total camber change (deg) across the mm stroke, with its value at the nominal heights. Each (deg/mm) is the local linear sensitivity at the nominal point, estimated either by finite differences or by regression slope.
$r_i^2$ as a variance share
Because and are independent, the squared sample correlation between and input estimates the fraction of explained linearly by input alone. For a purely linear response with independent inputs, approaches ; any shortfall reflects nonlinearity or sampling noise.
Maths applied §1.2 models a double wishbone in front view: two arms turning about inner pivots and , joined by a rigid upright. Its output is the camber change over mm of wheel travel. Suppose the two inner pivot heights are only known to a scatter each, independently. What is the spread of the camber change, and which pivot causes it?
This is an average over the inputs, so it is Monte Carlo. Draw 2000 geometries, solve each (two circles meet, then a bisection for the arm angle that gives mm), and read the output's distribution. The regression of §5 then splits the spread. Write for the error in input . For a nearly linear response with independent inputs, ; the fitted slope on input estimates the sensitivity , and estimates its share.
Reveal result (lock in your prediction above first)
Nominal camber runs from -0.13° to -2.08°, a fall of 1.95° (the book's 1.95°). Dashed: ±0.1° around it, the chapter's tolerance.
| quantity | value |
|---|---|
| mean, and its SE | 1.948°, 0.0021° |
| standard deviation (sampled; linear ) | 0.0957°; 0.0959° |
| 95% of builds between | 1.764° and 2.138° |
| builds more than 0.1° from nominal | 29.7% |
| slope on the lower pivot (finite difference) | +0.0272 °/mm (+0.0281), = 0.33 |
| slope on the upper pivot (finite difference) | -0.0382 °/mm (-0.0388), = 0.65 |
The two shares sum to 0.98: the response is close to linear over this scatter, so the linear spread and the sampled one agree. The sampling needed no derivative; it would work as well for an output with a kink. The S track asks the same question of the full otkd model, where the sampling and the reading are the same and each sample is a 3-D solve.
When a sampled sensitivity study breaks
- Assumes: the input distributions are right, independent, and the model holds over the whole sampled range
- When it fails: a shared cause (one fixture drilling both pivots) correlates the inputs and the spread changes; outside the model's range the samples describe the model, not the car
- Check: the shares should sum to near 1, and the sampled spread should match ; if not, the response is non-linear or the inputs interact
Practice
Hint 1
, so .
Hint 2
The error must fall by a factor of 4, so rises by .
Mixed practice: which method, and why?
Check yourself (closed book)
Keep these:
- An integral is an expectation; the sample mean estimates it with , order in .
- That rate does not depend on dimension; a product rule's does, so past sampling wins. The constant may still grow.
- Estimate the bar with , report the seed with it, and remember the 95% is asymptotic: few or skewed samples cover less.
- Variance reduction changes the constant: a control variate leaves ; antithetic pairs need a monotone integrand.
- Least squares projects onto the columns of ; the slope is a weighted average of slopes, , and .
- A sensitivity study samples the inputs and reads the output's spread; the regression slope is the sensitivity and is the input's share.
Your connection
Pick one number in your own work that depends on an input you only know to a tolerance. How many samples would you need to state its spread to two significant figures, and what would you report alongside it?
Answers
Practice A. .
Practice B. , since the error falls by 4 and rises by 16.
Practice C. .
Mixed practice. a product quadrature rule (2-D, smooth, high accuracy); Monte Carlo over the twelve inputs; order about one half.
Where the maths is derived
Optional. These notes give the intuition and application; the sources below give the full derivations and proofs.
§1 Monte Carlo integration and its rate
- Robert and Casella (2004), Monte Carlo Statistical Methods: the Monte Carlo estimator of an integral, its variance, and the central limit theorem behind the error.
§3 Error bars, coverage and seeds
- Robert and Casella (2004), Monte Carlo Statistical Methods: confidence intervals from the sample variance, and pseudo-random generators.
§4 Variance reduction
- Robert and Casella (2004), Monte Carlo Statistical Methods: antithetic variables and control variates, and the variance each leaves.
§5 Regression as averaging
- Trefethen and Bau (1997), Numerical Linear Algebra: least squares as an orthogonal projection, the normal equations, and why QR is preferred to forming .
Compiled from notebooks/methods/m07_averaging_and_monte_carlo.py — run locally with cd notebooks && uv run marimo edit methods/m07_averaging_and_monte_carlo.py for live Python scratch cells.
Back to the book: Averaging · An average, and its error bar