Numerical Methods

All books

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 1/(1−ρ2)1/(1-\rho^2)
  • read a least-squares line as a projection and a weighted average, and relate the slope to rr
  • 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.

Predict first. Try first: estimate ∫[0,1]8∏j=18π2sin⁡(πxj) dx=1\int_{[0,1]^8} \prod_{j=1}^{8} \tfrac{\pi}{2}\sin(\pi x_j)\,\mathrm{d}x = 1 with 65 536=4865\,536 = 4^8 evaluations, either a product midpoint rule (4 points per axis) or plain Monte Carlo. Which is more accurate?

Choose a prediction

Check answer (without scripting)

Answer: Monte Carlo, by more than ten times. The rule's error is O(N−2/d)=O(N−1/4)O(N^{-2/d}) = O(N^{-1/4}) at d=8d = 8; Monte Carlo's is σd/N\sigma_d/\sqrt N whatever dd. §2 measures the gap.

Warm-up: remember

Closed book, from earlier notebooks. Answer before you read on.

1. The explicit heat scheme has growth factor g(θ)=1−4rsin⁡2(θ/2)g(\theta) = 1 - 4r\sin^2(\theta/2). Which mode decides the limit r≤1/2r \le 1/2?

Question 1
How sure?

2. Inverse iteration multiplies by (A−σI)−1(A - \sigma I)^{-1}. Which eigenvalue of AA does it find?

Question 2
How sure?

3. Elimination without row swaps on (10−20111)x=(1,2)\begin{pmatrix} 10^{-20} & 1 \\ 1 & 1 \end{pmatrix} x = (1, 2) returns x1=0x_1 = 0, although κ∞(A)=4\kappa_\infty(A) = 4. Who is to blame?

Question 3
How sure?

Show answers and explanations

1. The grid-scale sawtooth, θ = π. g(π)=1−4rg(\pi) = 1 - 4r, and ∣1−4r∣≤1|1 - 4r| \le 1 needs r≤1/2r \le 1/2. The mode that alternates sign from node to node is the first to grow.

2. The one nearest sigma. (A−σI)−1(A - \sigma I)^{-1} has eigenvalues 1/(λi−σ)1/(\lambda_i - \sigma), largest for the λi\lambda_i nearest σ\sigma; power iteration on it converges at ∣λnear−σ∣/∣λnext−σ∣|\lambda_{\text{near}} - \sigma| / |\lambda_{\text{next}} - \sigma|.

3. The algorithm: the multiplier 1e20 swamps the second row. u22=1−1020u_{22} = 1 - 10^{20} rounds to −1020-10^{20}, so the 1 in row 2 is lost. Partial pivoting keeps every multiplier at most 1 in size and avoids it.

1. Monte Carlo integration and its rate

Setting: the problem, its sets and its symbols

Problem. Given the probability space (Ω,F,P)(\Omega, \mathcal{F}, P) with Ω=[0,1]2\Omega = [0,1]^2 and PP uniform, an integrand g:Ω→Rg : \Omega \to \mathbb{R} and i.i.d. samples X1,…,XN∼PX_1, \dots, X_N \sim P, find I=E[g(X)]I = \mathbb{E}[g(X)] by the sample mean I^N\hat I_N, and find the order α\alpha such that the RMS error eN≈CN−αe_N \approx C N^{-\alpha} as N→∞N \to \infty.

Symbol In Meaning
(Ω,F,P)(\Omega, \mathcal{F}, P) Ω=[0,1]2\Omega = [0,1]^2 the probability space: PP is area on the unit square
pp Ω→[0,∞)\Omega \to [0, \infty) the density of PP; here p=1p = 1 on Ω\Omega
DD {(x,y)∈Ω:x2+y2≤1}\{(x, y) \in \Omega : x^2 + y^2 \le 1\} the quarter disc, of area π/4\pi/4
gg Ω→{0,4}\Omega \to \{0, 4\} the integrand 4⋅1D4 \cdot \mathbf{1}_D
II R\mathbb{R} the target ∫g p=E[g(X)]\int g\,p = \mathbb{E}[g(X)], here π\pi
XiX_i i.i.d. on (Ω,F,P)\text{i.i.d. on } (\Omega, \mathcal{F}, P) the sample points, i=1,…,Ni = 1, \dots, N
NN N\mathbb{N} the sample size, 100⋅4k100 \cdot 4^k in row kk of the table
I^N\hat I_N ΩN→R\Omega^N \to \mathbb{R} the estimator 1N∑i=1Ng(Xi)\frac1N \sum_{i=1}^N g(X_i), a random variable
σ2\sigma^2 [0,∞)[0, \infty) Var⁡g(X)\operatorname{Var} g(X), the variance of one sample
eNe_N [0,∞)[0, \infty) the RMS error E(I^N−I)2\sqrt{\mathbb{E}(\hat I_N - I)^2}, measured over 64 independent runs
α\alpha R\mathbb{R} the observed order log⁡4(eN/e4N)\log_4(e_N / e_{4N}), the table's last column
s, p^, ns,\ \hat p,\ n {0,…,232−1}, [0,1], N\{0, \dots, 2^{32} - 1\},\ [0, 1],\ \mathbb{N} in the kernel: the generator's state, the fraction of points in DD, and the point count
How these symbols connect

The uniform density p=1p = 1 on Ω=[0,1]2\Omega = [0,1]^2 turns the area integral of g=4⋅1Dg = 4 \cdot \mathbf{1}_D into the expectation I=E[g(X)]I = \mathbb{E}[g(X)], with single-sample variance σ2\sigma^2. Drawing N=100⋅4kN = 100 \cdot 4^k i.i.d. points X1,…,XNX_1, \dots, X_N produces the random estimator I^N\hat I_N; repeating 64 independent runs yields the RMS error eNe_N, and successive ratios log⁡4(eN/e4N)\log_4(e_N / e_{4N}) measure the empirical order α\alpha. In the Rust kernel, an LCG updates state ss to count hits p^\hat p out of nn points.

Symbol-by-symbol notes
$(\Omega, \mathcal{F}, P)$ and $p$

(Ω,F,P)(\Omega, \mathcal{F}, P) is the probability space: sample space Ω=[0,1]2\Omega = [0,1]^2, event σ\sigma-algebra F\mathcal{F} and probability measure PP. Because PP is uniform on the unit square of area 11, its density is p=1p = 1 on Ω\Omega, so E[g(X)]\mathbb{E}[g(X)] equals the ordinary area integral ∫Ωg(x,y) dx dy\int_\Omega g(x, y)\,\mathrm{d}x\,\mathrm{d}y.

$g = 4 \cdot \mathbf{1}_D$ and $\sigma^2$

The indicator 1D(x,y)\mathbf{1}_D(x, y) equals 11 inside the quarter disc DD and 00 outside, so g(X)g(X) takes only the values 00 and 44. Its variance σ2=Var⁡g(X)\sigma^2 = \operatorname{Var} g(X) is a fixed property of a single draw, independent of NN.

$\hat I\lt em>N$ versus $I$ and $e\lt /em>N$

II is a fixed real number (here π\pi), whereas I^N:ΩN→R\hat I_N : \Omega^N \to \mathbb{R} is a random variable whose single-run error fluctuates from seed to seed. The RMS error eN=E(I^N−I)2e_N = \sqrt{\mathbb{E}(\hat I_N - I)^2} averages squared errors over 64 independent runs so the scaling with NN can be read cleanly.

$\alpha$ and the kernel triple $(s, \hat p, n)$

Because each table row quadruples NN, the observed order α=log⁡4(eN/e4N)\alpha = \log_4(e_N / e_{4N}) uses base 44 so that eN∝N−αe_N \propto N^{-\alpha} reads off α\alpha directly. In the Rust kernel, ss is an unsigned 32-bit LCG state (not a sample standard deviation), p^∈[0,1]\hat p \in [0, 1] is the hit fraction (so 4p^4\hat p estimates π\pi), and nn is the point count.

Drop points uniformly in the unit square and count the fraction inside the quarter circle x2+y2≤1x^2 + y^2 \le 1. That fraction estimates the area π/4\pi/4, so four times it estimates π\pi. In general, an integral is an expectation,

I=∫g(x) p(x) dx=E[g(X)],I^N=1N∑i=1Ng(Xi),I = \int g(x)\,p(x)\,\mathrm{d}x = \mathbb{E}[g(X)], \qquad \hat I_N = \frac{1}{N}\sum_{i=1}^{N} g(X_i),

with XiX_i drawn from pp. Here pp is uniform on the square and g=4⋅1{x2+y2≤1}g = 4 \cdot \mathbf{1}\{x^2 + y^2 \le 1\}.

A single run's error is random, so the table measures the root-mean-square error over 64 independent runs at each NN, in M01's convergence table: NN grows by 4 a row, and the order column is log⁡4\log_4 of successive error ratios. Before deriving anything, predict how fast the error falls.

Predict first. Each row has four times the samples of the one before. The RMS error shrinks by about

Choose a prediction

Check answer (without scripting)

Answer: a factor of 2. σ/4N=12 σ/N\sigma/\sqrt{4N} = \tfrac12\,\sigma/\sqrt N: order 12\tfrac12. The order column scatters about 0.5 because each entry is itself an estimate.

Why. The estimator is unbiased by linearity of expectation. Independence kills the cross terms in its variance:

Var⁡I^N=1N2∑i=1NVar⁡g(Xi)=σ2N,SE=σN.\operatorname{Var}\hat I_N = \frac{1}{N^2}\sum_{i=1}^{N}\operatorname{Var} g(X_i) = \frac{\sigma^2}{N}, \qquad \mathrm{SE} = \frac{\sigma}{\sqrt N}.

So the error has order 12\tfrac12 in NN. For the quarter circle gg is 4 times a coin with P(inside)=π/4P(\text{inside}) = \pi/4, so σ=4(π/4)(1−π/4)\sigma = 4\sqrt{(\pi/4)(1 - \pi/4)}. The reveal compares the measured table with this prediction.

Reveal result (lock in your prediction above first)
10²10³10⁴10⁵10⁻²10⁻¹RMS errorσ/√Nsamples Nerror
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 NN halves the error. Here σ=1.642\sigma = 1.642. The order column wanders because each RMS is itself a 64-run estimate; a least-squares slope of log⁡\log error on log⁡N\log N 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), s←1664525 s+1013904223 mod 232s \leftarrow 1664525\,s + 1013904223 \bmod 2^{32}, keeping the top 24 bits; each step draws a batch of points and reports 4p^4\hat p and 4p^(1−p^)/n4\sqrt{\hat p(1-\hat p)/n}, 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 N−1/2N^{-1/2} and ss never settles; with correlated samples the true error is larger than s/Ns/\sqrt N says
  • Check: the order column of the convergence table should settle near 0.5, and ss should stop drifting as NN grows

2. Dimension: Monte Carlo against a grid as the dimension grows

Setting: the problem, its sets and its symbols

Problem. Given a dimension dd and an integrand f:[0,1]d→Rf : [0,1]^d \to \mathbb{R}, find Id=∫[0,1]df(x) dxI_d = \int_{[0,1]^d} f(x)\,\mathrm{d}x from NN evaluations of ff, and compare the error of the product midpoint rule QmdQ_m^d with that of the Monte Carlo mean I^N\hat I_N at the same NN.

Symbol In Meaning
dd {1,…,10}\{1, \dots, 10\} the dimension (the slider)
x=(x1,…,xd)x = (x_1, \dots, x_d) [0,1]d[0,1]^d a point of the unit cube
ff [0,1]d→[0,∞)[0,1]^d \to [0, \infty) f(x)=∏j=1dπ2sin⁡(πxj)f(x) = \prod_{j=1}^{d} \tfrac{\pi}{2}\sin(\pi x_j)
IdI_d R\mathbb{R} the target ∫f\int f, equal to 1 for every dd
NN N\mathbb{N} evaluations of ff: N=mdN = m^d for the rule, any NN for Monte Carlo
mm N\mathbb{N} midpoint-rule points per axis
QmdQ_m^d R\mathbb{R} the product midpoint rule: the mean of ff over the mdm^d cell centres
XiX_i i.i.d. uniform on [0,1]d\text{i.i.d. uniform on } [0,1]^d the Monte Carlo points, i=1,…,Ni = 1, \dots, N
I^N\hat I_N R\mathbb{R} the Monte Carlo mean 1N∑if(Xi)\frac1N \sum_i f(X_i)
σd2\sigma_d^2 [0,∞)[0, \infty) Var⁡f(X)\operatorname{Var} f(X) for XX uniform on [0,1]d[0,1]^d
Erule, EMCE_{\text{rule}},\ E_{\text{MC}} [0,∞)[0, \infty) the rule's error ∣Qmd−Id∣\lvert Q_m^d - I_d \rvert, and Monte Carlo's RMS error over 16 runs
How these symbols connect

Choosing the dimension dd fixes the unit cube [0,1]d[0,1]^d and the product integrand ff, whose exact integral is Id=1I_d = 1. On the grid side, placing mm midpoints along each axis requires N=mdN = m^d evaluations and produces the deterministic rule QmdQ_m^d with error Erule=∣Qmd−Id∣E_{\text{rule}} = \lvert Q_m^d - I_d \rvert. On the sampling side, NN i.i.d. uniform draws Xi∈[0,1]dX_i \in [0,1]^d form I^N\hat I_N, whose per-sample variance is σd2\sigma_d^2 and whose RMS error EMCE_{\text{MC}} is measured across 16 runs at the same evaluation budget NN.

Symbol-by-symbol notes
$f$ and $I_d$

f(x)=∏j=1dπ2sin⁡(πxj)f(x) = \prod_{j=1}^{d} \tfrac{\pi}{2}\sin(\pi x_j) is separable across coordinates. Each one-dimensional factor integrates to 11 on [0,1][0,1], so Id=1I_d = 1 in every dimension and the product rule QmdQ_m^d equals the 1-D midpoint rule raised to the power dd.

$m$ versus $N$

mm is the number of grid cells per coordinate axis, whereas NN is the total count of function evaluations. For the product rule they are coupled by N=mdN = m^d, while Monte Carlo accepts any positive integer NN.

$\sigma_d^2$

σd2=Var⁡f(X)\sigma_d^2 = \operatorname{Var} f(X) is the variance of a single uniform draw on [0,1]d[0,1]^d. Unlike Id=1I_d = 1, it depends on dd because the product concentrates more strongly near the centre of the cube as dd grows.

$E\lt em>{\text{rule}}$ versus $E\lt /em>{\text{MC}}$

Erule=∣Qmd−Id∣E_{\text{rule}} = \lvert Q_m^d - I_d \rvert is deterministic and computed exactly for each (m,d)(m, d), whereas EMCE_{\text{MC}} is estimated as the root-mean-square error of I^N\hat I_N across 16 independent runs at each NN.

Take f(x)=∏j=1dπ2sin⁡(πxj)f(x) = \prod_{j=1}^{d} \tfrac{\pi}{2}\sin(\pi x_j) on [0,1]d[0,1]^d; each factor integrates to 1, so I=1I = 1 in every dimension. A product midpoint rule with mm points per axis uses N=mdN = m^d points. Its error per axis is O(m−2)O(m^{-2}), so

Erule=O(m−2)=O ⁣(N−2/d),EMC=σdN,σd2=(π28)d−1.E_{\text{rule}} = O(m^{-2}) = O\!\left(N^{-2/d}\right), \qquad E_{\text{MC}} = \frac{\sigma_d}{\sqrt N}, \quad \sigma_d^2 = \left(\tfrac{\pi^2}{8}\right)^{d} - 1.

The rule's order in NN is 2/d2/d: excellent at d=1d = 1, equal to Monte Carlo's at d=4d = 4, worse beyond. Because ff is a product, the rule's value is the 1-D rule's value to the power dd, so its error is computed exactly even at 10710^7 points. The Monte Carlo points are the RMS of 16 independent runs. Move dd and watch the rule's line flatten while Monte Carlo's keeps its slope.

Reveal result (lock in your prediction above first)

At d=8d = 8 and N=65 536N = 65\,536: the midpoint rule's error is 0.230, Monte Carlo's standard error is 0.0082, about 28 times smaller.

10¹10³10⁵10⁷10⁻³10⁻²10⁻¹10⁰midpoint ruleMonte Carlo (RMS of 16)σ_d/√Nfunction evaluations N|error|

Fitted orders at d=8d = 8: midpoint rule 0.29 (theory 2/d=0.252/d = 0.25), Monte Carlo 0.49 (theory 0.5). The rate is dimension-free; the constant is not. σd\sigma_d grows with dd, which lifts the Monte Carlo line without tilting it.

When Monte Carlo in many dimensions breaks
  • Assumes: the integrand's standard deviation σd\sigma_d stays moderate as dd grows
  • When it fails: a product of many factors can have σd\sigma_d growing exponentially in dd: the rate survives but the constant does not, and rare large values dominate
  • Check: report s/Ns/\sqrt N from the run itself; if ss 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 X1,…,XNX_1, \dots, X_N with unknown mean μ\mu and variance σ2\sigma^2, find an interval CNC_N, computed from the samples alone, that aims at P(μ∈CN)=0.95P(\mu \in C_N) = 0.95; then measure its actual coverage P(μ∈CN)P(\mu \in C_N) by repetition. Separately, given a seed ξ0\xi_0, find the run it determines.

Symbol In Meaning
X1,…,XNX_1, \dots, X_N i.i.d. on (Ω,F,P)\text{i.i.d. on } (\Omega, \mathcal{F}, P) the samples: standard normal, §1's π\pi indicator, or exponential with mean 1
μ, σ2\mu,\ \sigma^2 R, (0,∞)\mathbb{R},\ (0, \infty) their true mean and variance, unknown to the estimator
Xˉ\bar X R\mathbb{R} the sample mean 1N∑iXi\frac1N \sum_i X_i
s2s^2 [0,∞)[0, \infty) the sample variance, with divisor N−1N - 1
zz (0,∞)(0, \infty) the normal quantile; z=1.96z = 1.96 for a nominal 95%
CNC_N closed intervals in R\text{closed intervals in } \mathbb{R} Xˉ±z s/N\bar X \pm z\,s/\sqrt N, random through the samples
SE\mathrm{SE} [0,∞)[0, \infty) the estimated standard error s/Ns/\sqrt N; the seed table uses the binomial form 4p^(1−p^)/N4\sqrt{\hat p(1-\hat p)/N}, with p^\hat p the fraction of points in the quarter disc
P(μ∈CN)P(\mu \in C_N) [0,1][0, 1] the coverage, estimated as the fraction of 4000 repeats whose interval contains μ\mu
ξk\xi_k {0,…,232−1}\{0, \dots, 2^{32} - 1\} the generator's state; ξ0\xi_0 is the seed and ξk+1=(1664525 ξk+1013904223) mod 232\xi_{k+1} = (1664525\,\xi_k + 1013904223) \bmod 2^{32}
How these symbols connect

From NN i.i.d. samples X1,…,XNX_1, \dots, X_N with unknown mean μ\mu and variance σ2\sigma^2, the sample mean Xˉ\bar X and sample variance s2s^2 yield the estimated standard error SE=s/N\mathrm{SE} = s/\sqrt N. Combining Xˉ\bar X, SE\mathrm{SE} and the normal quantile z=1.96z = 1.96 builds the random interval CNC_N, whose empirical coverage P(μ∈CN)P(\mu \in C_N) is measured over 4000 repeats. Separately, choosing an initial seed ξ0\xi_0 drives the recurrence ξk+1\xi_{k+1} to generate a reproducible stream of draws and a repeatable estimate with its binomial SE\mathrm{SE}.

Symbol-by-symbol notes
$s^2$ versus $\sigma^2$

σ2\sigma^2 is the fixed, unknown population variance of the distribution, whereas s2=1N−1∑i=1N(Xi−Xˉ)2s^2 = \tfrac{1}{N-1}\sum_{i=1}^N (X_i - \bar X)^2 is a random estimate computed from the NN draws. The divisor N−1N - 1 accounts for measuring deviations from Xˉ\bar X rather than from the unknown μ\mu.

$C\lt em>N$ and $P(\mu \in C\lt /em>N)$

The true mean μ\mu is fixed; the interval CN=[Xˉ−z SE, Xˉ+z SE]C_N = [\bar X - z\,\mathrm{SE},\, \bar X + z\,\mathrm{SE}] is the random object that shifts and changes width on every sample. Coverage P(μ∈CN)P(\mu \in C_N) 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 SE=s/N\mathrm{SE} = s/\sqrt N. In the seed table for the quarter-disc π\pi estimator, each draw is a Bernoulli hit scaled by 44 with sample fraction p^\hat p, so the kernel computes SE=4p^(1−p^)/N\mathrm{SE} = 4\sqrt{\hat p(1 - \hat p)/N}.

$\xi\lt em>k$ and the seed $\xi\lt /em>0$

This section denotes the LCG state by ξk\xi_k rather than §1's ss so it does not collide with the sample standard deviation ss. Fixing the integer seed ξ0\xi_0 fixes the entire sequence ξ1,ξ2,…\xi_1, \xi_2, \dots deterministically.

σ\sigma is as unknown as II. Replace it with the sample variance, whose N−1N-1 pays for measuring deviations from Xˉ\bar X rather than from the true mean:

s2=1N−1∑i=1N(Xi−Xˉ)2,Xˉ±z sN.s^2 = \frac{1}{N-1}\sum_{i=1}^{N}\left(X_i - \bar X\right)^2, \qquad \bar X \pm z\,\frac{s}{\sqrt N}.

By the central limit theorem Xˉ\bar X is close to normal for large NN, so z=1.96z = 1.96 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.

Predict first. Draw N=5N = 5 values from the exponential distribution (mean 1, strongly skewed) and form Xˉ±1.96 s/5\bar X \pm 1.96\,s/\sqrt 5. Over 4000 repeats, the interval contains 1 about

Choose a prediction

Check answer (without scripting)

Answer: 80% of the time. Five draws give a noisy ss that is often too small, and the skew leaves Xˉ\bar X far from normal. The bar is too short about one time in five.

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 N=5N = 5 the exponential covers 80.8% and even the normal only 88.0% (for a normal, the shortfall is exactly what Student's tt corrects). The π indicator covers 70.0%: with probability (π/4)5=0.299(\pi/4)^5 = 0.299 all five points land inside, s=0s = 0, and the bar has zero width. By N=1000N = 1000 all three are within sampling noise of 95%.

When the 95% interval breaks
  • Assumes: NN is large enough that Xˉ\bar X is close to normal and ss close to σ\sigma
  • When it fails: at small NN or with a skewed or heavy-tailed output the coverage falls below 95% (81% for the exponential at N=5N = 5 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 UU uniform on [0,1][0,1] and f(u)=euf(u) = e^u, find an unbiased estimator of I=E[f(U)]I = \mathbb{E}[f(U)] with less variance per evaluation of ff than plain sampling: find c∗∈Rc^* \in \mathbb{R} minimising Var⁡Yc\operatorname{Var} Y_c, and compare Yc∗Y_{c^*} and the antithetic pair YAY_A with f(U)f(U).

Symbol In Meaning
UU uniform on [0,1]\text{uniform on } [0,1] one sample, with known mean E U=12\mathbb{E}\,U = \tfrac12
ff [0,1]→R[0,1] \to \mathbb{R} the integrand f(u)=euf(u) = e^u
II R\mathbb{R} the target ∫01ex dx=e−1\int_0^1 e^x\,\mathrm{d}x = e - 1
σf2\sigma_f^2 (0,∞)(0, \infty) Var⁡f(U)\operatorname{Var} f(U), the plain estimator's variance per sample
cc R\mathbb{R} the control coefficient (the slider)
YcY_c R\mathbb{R} the control-variate sample eU−c (U−12)e^U - c\,(U - \tfrac12)
c∗c^* R\mathbb{R} the minimiser of c↦Var⁡Ycc \mapsto \operatorname{Var} Y_c
ρ\rho [−1,1][-1, 1] the correlation Corr⁡(eU,U)\operatorname{Corr}(e^U, U)
YAY_A R\mathbb{R} the antithetic pair 12(eU+e1−U)\tfrac12(e^U + e^{1-U}), which costs two evaluations
How these symbols connect

A uniform draw UU on [0,1][0,1] feeds both the integrand f(U)=eUf(U) = e^U (with target mean II and baseline variance σf2\sigma_f^2) and the zero-mean control term c (U−12)c\,(U - \tfrac12) to form the unbiased estimator YcY_c. Varying cc traces Var⁡Yc\operatorname{Var} Y_c down to its minimum at c∗c^*, governed by the correlation ρ=Corr⁡(eU,U)\rho = \operatorname{Corr}(e^U, U), while pairing UU with 1−U1 - U defines the antithetic average YAY_A at twice the evaluation cost per sample.

Symbol-by-symbol notes
$Y_c$ and $c$ versus $c^*$

Because E[U−12]=0\mathbb{E}[U - \tfrac12] = 0, Yc=eU−c (U−12)Y_c = e^U - c\,(U - \tfrac12) is unbiased for every c∈Rc \in \mathbb{R}, not only at the optimum. The slider sweeps cc, while c∗c^* marks the unique minimiser of c↦Var⁡Ycc \mapsto \operatorname{Var} Y_c.

$\rho$ and $\sigma_f^2$

σf2=Var⁡f(U)\sigma_f^2 = \operatorname{Var} f(U) is the plain estimator's variance per draw, and ρ=Corr⁡(eU,U)∈[−1,1]\rho = \operatorname{Corr}(e^U, U) \in [-1, 1] is the dimensionless linear correlation between the integrand and the control variate. Both are fixed properties of (eU,U)(e^U, U) on [0,1][0, 1].

$Y_A$ and cost per evaluation

One antithetic sample YA=12(eU+e1−U)Y_A = \tfrac12(e^U + e^{1-U}) requires two evaluations of ff rather than one. Comparing YAY_A fairly against plain sampling or YcY_c accounts for that factor of two in evaluation budget, not just variance per sample.

The rate is fixed at N−1/2N^{-1/2}; the constant σ\sigma is not. Every halving of σ\sigma saves a factor of four in samples. Take I=∫01ex dx=e−1I = \int_0^1 e^x\,\mathrm{d}x = e - 1, with UU uniform on [0,1][0,1].

Control variate. UU itself has known mean 12\tfrac12 and tracks eUe^U. For any cc, Yc=eU−c (U−12)Y_c = e^U - c\,(U - \tfrac12) is still unbiased, with

Var⁡Yc=σf2−2c Cov⁡(eU,U)+c2Var⁡U.\operatorname{Var} Y_c = \sigma_f^2 - 2c\,\operatorname{Cov}(e^U, U) + c^2 \operatorname{Var} U .

A quadratic in cc, smallest at c∗=Cov⁡(eU,U)/Var⁡Uc^* = \operatorname{Cov}(e^U, U)/\operatorname{Var}U, where it equals σf2(1−ρ2)\sigma_f^2(1 - \rho^2). So the factor gained is 1/(1−ρ2)1/(1-\rho^2): ρ=0.9\rho = 0.9 buys about 5, ρ=0.99\rho = 0.99 about 50.

Antithetic pairs. Average eUe^U and e1−Ue^{1-U}. A pair costs two evaluations and has variance 12(σf2+Cov⁡(eU,e1−U))\tfrac12(\sigma_f^2 + \operatorname{Cov}(e^U, e^{1-U})). Because exe^x is monotone the covariance is negative, so a pair beats two independent draws.

Move cc: the sampled variance of YcY_c traces the parabola.

Figure 1

Predict first. At the best cc, the control variate UU cuts the variance of the eUe^U estimator by a factor of about

Choose a prediction

Check answer (without scripting)

Answer: 60. ρ(eU,U)≈0.992\rho(e^U, U) \approx 0.992, so 1/(1−ρ2)≈611/(1-\rho^2) \approx 61: the same accuracy for one sixtieth of the samples.

Reveal result (lock in your prediction above first)
00.751.52.25310⁻²10⁻¹coefficient cVar of one sample
estimator variance per sample per evaluation, against plain
plain eUe^U 0.2420 1
control, c=0.00c = 0.00 (sampled) 0.24452 1.0
control, c∗=1.690c^* = 1.690 (exact) 0.00394 61.4
antithetic pair (exact; sampled 0.00392) 0.00391 30.9

ρ=0.9918\rho = 0.9918, and 1/(1−ρ2)=61.41/(1-\rho^2) = 61.4. The antithetic factor is per evaluation: a pair costs two. Note what c∗c^* is: Cov⁡/Var⁡\operatorname{Cov}/\operatorname{Var}, the least-squares slope of eUe^U on UU. 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 ff and its mean is known exactly; for antithetic pairs, ff is monotone
  • When it fails: a weak correlation buys only 1/(1−ρ2)1/(1-\rho^2), near 1; a control with an estimated mean brings that estimate's error with it; a symmetric ff 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 (xi,yi)∈R2(x_i, y_i) \in \mathbb{R}^2, i=1,…,ni = 1, \dots, n, find β^=(a,b)∈R2\hat\beta = (a, b) \in \mathbb{R}^2 minimising S(a,b)=∑i(yi−a−bxi)2=∥y−Xβ∥2S(a, b) = \sum_i (y_i - a - b x_i)^2 = \lVert y - X\beta \rVert^2. Then find the reverse fit (a′,b′)(a', b') minimising ∑i(xi−a′−b′yi)2\sum_i (x_i - a' - b' y_i)^2, and compare the two lines in the same axes.

Symbol In Meaning
nn N\mathbb{N} the number of points, here 5
x, yx,\ y Rn\mathbb{R}^n the data: x=(0,1,2,3,4)x = (0, 1, 2, 3, 4), y=(1.1,1.9,3.2,3.8,y5)y = (1.1, 1.9, 3.2, 3.8, y_5), with y5y_5 on the slider
XX Rn×2\mathbb{R}^{n \times 2} the design matrix [1   x][\mathbf{1}\;\, x]
β=(a,b)\beta = (a, b) R2\mathbb{R}^2 intercept and slope, the unknowns; β^\hat\beta is the minimiser
SS R2→[0,∞)\mathbb{R}^2 \to [0, \infty) the sum of squared vertical residuals
ee Rn\mathbb{R}^n the residual y−Xβ^y - X\hat\beta
xˉ, yˉ\bar x,\ \bar y R\mathbb{R} the means of xx and yy
Sxx, Syy, SxyS_{xx},\ S_{yy},\ S_{xy} R\mathbb{R} ∑i(xi−xˉ)2\sum_i (x_i - \bar x)^2, ∑i(yi−yˉ)2\sum_i (y_i - \bar y)^2 and ∑i(xi−xˉ)(yi−yˉ)\sum_i (x_i - \bar x)(y_i - \bar y)
mim_i R\mathbb{R} the slope from (xˉ,yˉ)(\bar x, \bar y) to point ii, for xi≠xˉx_i \ne \bar x
rr [−1,1][-1, 1] the correlation coefficient Sxy/SxxSyyS_{xy}/\sqrt{S_{xx} S_{yy}}
sx, sys_x,\ s_y [0,∞)[0, \infty) the standard deviations of xx and yy
s, SE(b)s,\ \mathrm{SE}(b) [0,∞)[0, \infty) the residual standard deviation, s2=∑iei2/(n−2)s^2 = \sum_i e_i^2/(n - 2), and the slope's standard error
(a′,b′)(a', b') R2\mathbb{R}^2 the reverse fit x≈a′+b′yx \approx a' + b' y
How these symbols connect

The nn data pairs (xi,yi)(x_i, y_i) assemble into the design matrix X=[1   x]X = [\mathbf{1}\;\,x] and response vector yy; minimising S(a,b)=∥y−Xβ∥2S(a, b) = \lVert y - X\beta \rVert^2 selects β^=(a,b)\hat\beta = (a, b) and yields the residual vector e=y−Xβ^e = y - X\hat\beta. The means (xˉ,yˉ)(\bar x, \bar y) and centred sums Sxx,Syy,SxyS_{xx}, S_{yy}, S_{xy} express the fit through the pairwise slopes mim_i, the correlation rr and the spreads sx,sys_x, s_y, while ee gives the residual standard deviation ss and slope uncertainty SE(b)\mathrm{SE}(b). Swapping the roles of xx and yy defines the reverse fit (a′,b′)(a', b') from horizontal residuals so both lines can be plotted together.

Symbol-by-symbol notes
$X$, $\beta$ and $\hat\beta$

The design matrix X=[1   x]∈Rn×2X = [\mathbf{1}\;\,x] \in \mathbb{R}^{n \times 2} places a column of ones beside xx, so XβX\beta has entries a+bxia + b x_i. Here β=(a,b)\beta = (a, b) is any candidate parameter pair and β^\hat\beta is the minimiser of SS.

$S\lt em>{xx}, S\lt /em>{yy}, S\lt em>{xy}$ versus $s\lt /em>x, s_y$ and $r$

Sxx,Syy,SxyS_{xx}, S_{yy}, S_{xy} are unscaled centred sums of squares and cross-products, whereas sxs_x and sys_y divide by n−1n - 1 before taking the square root. The correlation r=Sxy/SxxSyyr = S_{xy}/\sqrt{S_{xx} S_{yy}} 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 mi=(yi−yˉ)/(xi−xˉ)m_i = (y_i - \bar y)/(x_i - \bar x) is the slope from the mean point (xˉ,yˉ)(\bar x, \bar y) to (xi,yi)(x_i, y_i). It is undefined when xi=xˉx_i = \bar x (here x3=2x_3 = 2), which carries zero weight (xi−xˉ)2=0(x_i - \bar x)^2 = 0 in the weighted average for bb.

$s$ versus $s_y$ and $\mathrm{SE}(b)$, and $(a', b')$

s=∑iei2/(n−2)s = \sqrt{\sum_i e_i^2/(n - 2)} is the residual standard deviation (with n−2n - 2 degrees of freedom for two fitted parameters), not the spread sys_y of yy itself; it sets the slope standard error SE(b)\mathrm{SE}(b). The primed pair (a′,b′)(a', b') minimises squared horizontal residuals xi−a′−b′yix_i - a' - b' y_i instead of vertical ones.

The book's five points: x=0,1,2,3,4x = 0, 1, 2, 3, 4 and y=1.1,1.9,3.2,3.8,5.1y = 1.1, 1.9, 3.2, 3.8, 5.1. Fit y≈a+bxy \approx a + bx by minimising S(a,b)=∑(yi−a−bxi)2S(a, b) = \sum (y_i - a - bx_i)^2. Setting both partial derivatives to zero gives the normal equations, which in matrix form, with X=[1   x]X = [\mathbf{1}\;\, x], are

X⊤(y−Xβ^)=0⟺X⊤X β^=X⊤y.X^\top (y - X\hat\beta) = 0 \quad\Longleftrightarrow\quad X^\top X\,\hat\beta = X^\top y .

Read the left form geometrically: the residual is orthogonal to every column of XX, so Xβ^X\hat\beta is the orthogonal projection of yy onto the plane spanned by 1\mathbf{1} and xx. The ones row says ∑ei=0\sum e_i = 0, so the line passes through (xˉ,yˉ)(\bar x, \bar y). The xx row then gives

b=SxySxx=∑i(xi−xˉ)2 mi∑i(xi−xˉ)2,mi=yi−yˉxi−xˉ:b = \frac{S_{xy}}{S_{xx}} = \frac{\sum_i (x_i - \bar x)^2 \, m_i}{\sum_i (x_i - \bar x)^2}, \qquad m_i = \frac{y_i - \bar y}{x_i - \bar x}:

a weighted average of the slopes from the mean point to each data point, the weights favouring points far from xˉ\bar x. That is why one distant point can move the line. The correlation coefficient r=Sxy/SxxSyyr = S_{xy}/\sqrt{S_{xx}S_{yy}} rescales the same sum, so b=r sy/sxb = r\,s_y/s_x; and SE(b)=s/Sxx\mathrm{SE}(b) = s/\sqrt{S_{xx}} with s2=∑ei2/(n−2)s^2 = \sum e_i^2/(n-2). Move the last point and watch bb, rr and the bar.

Predict first. Now regress xx on yy instead, minimising horizontal distances, and draw that line in the same axes. Compared with the yy-on-xx line it is

Choose a prediction

Check answer (without scripting)

Answer: steeper, and the two cross at the mean point. Both pass through (xˉ,yˉ)(\bar x, \bar y). In the xx–yy axes the swapped line has slope 1/b′=Syy/Sxy=b/r21/b' = S_{yy}/S_{xy} = b/r^2, which is steeper when ∣r∣<1|r| \lt 1.

Reveal result (lock in your prediction above first)
-0.50.7523.254.50.2911.452.63.754.91y on xx on yseriesxy
quantity value
slope bb, intercept aa 0.5700, 1.4600
weighted average of slopes to the mean point 0.5700
rr, and r2r^2 0.8314, 0.6913
b⋅b′b \cdot b' (slopes of yy on xx and xx on yy) 0.6913
SE(b)\mathrm{SE}(b), and b/SEb/\mathrm{SE} 0.2199, 2.6
max⁡∣X⊤e∣\max \lvert X^\top e \rvert 4.4e-15

At y5=3y_5 = 3 the scissors about the mean point is open. Slide to the book's y5=5.1y_5 = 5.1 and rr is so close to 1 that the lines almost coincide; the table then shows the page's numbers: b=0.99b = 0.99, SE=0.0597\mathrm{SE} = 0.0597, t=16.6t = 16.6. X⊤eX^\top e 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 X⊤XX^\top X squares the condition number, which is why large fits use QR on XX 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 s/Sxxs/\sqrt{S_{xx}} too small; one high-leverage point can move the slope a long way
  • Check: plot the residuals against xx and in order; X⊤e=0X^\top e = 0 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 δA∼N(0,σA2)\delta_A \sim N(0, \sigma_A^2) and δB∼N(0,σB2)\delta_B \sim N(0, \sigma_B^2) in the two inner pivot heights, and the map yy from those heights to the camber change over ±40\pm 40 mm of travel, find the distribution of y(zA0+δA, zB0+δB)y(z_A^0 + \delta_A,\ z_B^0 + \delta_B) (its mean, standard deviation and 95% range) and the share of Var⁡y\operatorname{Var} y owed to each input.

Symbol In Meaning
ii {A,B}\{A, B\} the input index: AA the lower arm's inner pivot, BB the upper arm's
ziz_i R\mathbb{R} the pivot heights (m); nominal zA0=0.155z_A^0 = 0.155, zB0=0.475z_B^0 = 0.475
δi\delta_i independent, N(0,σi2)\text{independent},\ N(0, \sigma_i^2) the errors in the two heights (mm)
σi\sigma_i [0,5][0, 5] their scatter (mm), the two sliders
ss [−40,40][-40, 40] wheel travel (mm)
θ\theta [−0.5,0.5][-0.5, 0.5] the lower arm's angle (rad), found by bisection so that the travel is ss
γ\gamma [−40,40]→R[-40, 40] \to \mathbb{R} camber (deg) as a function of travel, for one geometry
yy R2→R\mathbb{R}^2 \to \mathbb{R} the camber change γ(40)−γ(−40)\gamma(40) - \gamma(-40) (deg) as a function of (zA,zB)(z_A, z_B); y0y_0 at the nominal heights
kik_i R\mathbb{R} the sensitivity ∂y/∂zi\partial y/\partial z_i at the nominal heights (deg/mm)
NN N\mathbb{N} the number of sampled geometries, 2000
ri2r_i^2 [0,1][0, 1] the squared sample correlation of yy with input ii: its estimated share of Var⁡y\operatorname{Var} y
How these symbols connect

Independent normal errors δA,δB\delta_A, \delta_B (with slider spreads σA,σB\sigma_A, \sigma_B in mm) perturb the nominal inner pivot heights zA0,zB0z_A^0, z_B^0 (converted from mm to m). For each of N=2000N = 2000 sampled geometries, bisection solves for the lower-arm angle θ\theta that achieves wheel travel s=±40s = \pm 40 mm, evaluates camber γ(s)\gamma(s) (deg) and forms the camber change y=γ(40)−γ(−40)y = \gamma(40) - \gamma(-40). Regressing the sampled outputs yy on each input estimates its local sensitivity ki=∂y/∂zik_i = \partial y / \partial z_i (deg/mm) and variance share ri2r_i^2.

Symbol-by-symbol notes
$z\lt em>i$ (m) versus $\delta\lt /em>i$ and $\sigma_i$ (mm)

Nominal pivot heights zA0=0.155z_A^0 = 0.155 and zB0=0.475z_B^0 = 0.475 are in metres for the front-view geometry, while the perturbations δi∼N(0,σi2)\delta_i \sim N(0, \sigma_i^2) and slider spreads σi\sigma_i are in millimetres. The solver divides δi\delta_i by 10001000 before adding it to zi0z_i^0, and reports sensitivities kik_i in deg/mm.

$s$, $\theta$ and $\gamma(s)$

Wheel travel s∈[−40,40]s \in [-40, 40] mm is the target vertical displacement of the wheel centre, not the direct linkage input. For each geometry, bisection finds the lower-arm angle θ∈[−0.5,0.5]\theta \in [-0.5, 0.5] rad that matches s=±40s = \pm 40 mm, and γ(s)\gamma(s) reads the upright camber in degrees.

$y$ versus $y\lt em>0$ and $k\lt /em>i$

y(zA,zB)=γ(40)−γ(−40)y(z_A, z_B) = \gamma(40) - \gamma(-40) is the total camber change (deg) across the ±40\pm 40 mm stroke, with y0y_0 its value at the nominal heights. Each ki=∂y/∂zik_i = \partial y/\partial z_i (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 δA\delta_A and δB\delta_B are independent, the squared sample correlation ri2r_i^2 between yy and input ii estimates the fraction of Var⁡y\operatorname{Var} y explained linearly by input ii alone. For a purely linear response with independent inputs, rA2+rB2r_A^2 + r_B^2 approaches 11; any shortfall reflects nonlinearity or sampling noise.

Maths applied §1.2 models a double wishbone in front view: two arms turning about inner pivots AA and BB, joined by a rigid upright. Its output is the camber change over ±40\pm 40 mm of wheel travel. Suppose the two inner pivot heights are only known to a scatter σ\sigma 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 ±40\pm 40 mm), and read the output's distribution. The regression of §5 then splits the spread. Write δi\delta_i for the error in input ii. For a nearly linear response y≈y0+∑ikiδiy \approx y_0 + \sum_i k_i \delta_i with independent inputs, Var⁡y=∑iki2σi2\operatorname{Var} y = \sum_i k_i^2 \sigma_i^2; the fitted slope on input ii estimates the sensitivity kik_i, and ri2r_i^2 estimates its share.

Predict first. Both inner pivots scatter by the same σ=2\sigma = 2 mm. The lower arm is longer than the upper. Which pivot carries most of the spread in camber change?

Choose a prediction

Check answer (without scripting)

Answer: the upper pivot, about two thirds. The shorter upper arm turns a millimetre of pivot height into more angle: ∣kB∣>∣kA∣|k_B| > |k_A|, and the shares go as ki2σi2k_i^2\sigma_i^2.

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 ∑ki2σi2\sqrt{\sum k_i^2\sigma_i^2}) 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), r2r^2 = 0.33
slope on the upper pivot (finite difference) -0.0382 °/mm (-0.0388), r2r^2 = 0.65

The two r2r^2 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 r2r^2 shares should sum to near 1, and the sampled spread should match ∑i(kiσi)2\sqrt{\sum_i (k_i \sigma_i)^2}; if not, the response is non-linear or the inputs interact

Practice

Practice A (steps partly filled). A Monte Carlo run of N=10 000N = 10\,000 samples has sample standard deviation s=2.0s = 2.0. First SE=s/N=2.0/100=  ?\mathrm{SE} = s/\sqrt N = 2.0/100 = \;?; then the 95% half-width is 1.96×SE1.96 \times \mathrm{SE}. Enter the half-width.

Worked solution

SE=2.0/100=0.02\mathrm{SE} = 2.0/100 = 0.02; half-width =1.96×0.02=0.0392= 1.96 \times 0.02 = 0.0392.

Practice B (with a hint). At N=5000N = 5000 your estimate's standard error is 0.0120.012. How many samples give a standard error of 0.0030.003?

Worked solution

N=5000×(0.012/0.003)2=5000×16=80 000N = 5000 \times (0.012/0.003)^2 = 5000 \times 16 = 80\,000.

Hint 1

SE∝N−1/2\mathrm{SE} \propto N^{-1/2}, so N∝SE−2N \propto \mathrm{SE}^{-2}.

Hint 2

The error must fall by a factor of 4, so NN rises by 424^2.

Practice C (on your own). A cheap model correlates with the expensive one at ρ=0.95\rho = 0.95 and its mean is known exactly. Used as a control variate with the best coefficient, by what factor does it cut the number of samples for a given error bar?

Worked solution

The variance becomes σ2(1−ρ2)=0.0975 σ2\sigma^2(1-\rho^2) = 0.0975\,\sigma^2, so the samples needed fall by 1/(1−0.952)≈10.31/(1 - 0.95^2) \approx 10.3. At ρ=0.99\rho = 0.99 it would be about 50: the factor is all in the last digits of ρ\rho.

Mixed practice: which method, and why?

1. A smooth integrand on [0,1]2[0,1]^2, wanted to 10−810^{-8}.

Question 1

2. The mean camber change when twelve geometry inputs each scatter independently.

Question 2

3. Three Monte Carlo runs at NN, 4N4N, 16N16N give RMS errors 0.040, 0.021, 0.0098. What is the observed order in NN?

Question 3

Show answers and explanations

1. a product quadrature rule, checked with a convergence table. In two dimensions a smooth rule of order pp in hh is order p/2p/2 in NN, and Gauss or Simpson rules converge fast. M01's table confirms the order.

2. Monte Carlo over the inputs, with an error bar. The rate does not depend on the twelve dimensions, and the same samples give the spread and, by regression, each input's share.

3. about one half. log⁡4(0.040/0.021)≈0.46\log_4(0.040/0.021) \approx 0.46 and log⁡4(0.021/0.0098)≈0.55\log_4(0.021/0.0098) \approx 0.55: order 12\tfrac12, scattering as random errors do.

Check yourself (closed book)

1. A Monte Carlo estimate has a standard error of 0.030.03. To bring it to 0.0030.003 you need

Question 1
How sure?

2. At equal cost in eight dimensions, plain Monte Carlo beats a product midpoint rule. Why?

Question 2
How sure?

3. You draw N=5N = 5 values from a skewed distribution and quote Xˉ±1.96 s/N\bar X \pm 1.96\, s/\sqrt N. Over many repeats, how often does that interval cover the true mean?

Question 3
How sure?

4. A control variate hh with known mean has correlation ρ\rho with the integrand ff. At the best coefficient cc, the variance of f−c(h−Eh)f - c(h - \mathbb{E}h) is

Question 4
How sure?

5. You fit yy on xx (slope bb) and xx on yy (slope b′b'). The product b b′b\,b' is

Question 5
How sure?

6. In a sampled sensitivity study with independent inputs and a nearly linear response, what does r2r^2 of the output against one input estimate?

Question 6
How sure?

Show answers and explanations

1. 100 times the samples. σ/N\sigma/\sqrt{N} divided by 10 needs N\sqrt N multiplied by 10, so NN by 100: one more digit costs a hundredfold.

2. Its rate in N does not depend on d; the rule's falls to 2/d. The midpoint rule's error is O(m−2)O(m^{-2}) with N=mdN = m^d points, so O(N−2/d)O(N^{-2/d}). Monte Carlo's is σ/N\sigma/\sqrt N whatever dd. Past d=4d = 4 the rule's order is the smaller one.

3. Less than 95% of the time. With five draws ss is itself noisy and often too small, and the skew leaves Xˉ\bar X far from normal. Both shrink the coverage; the bar is honest only as NN grows.

4. σ² (1 − ρ²). At c∗=Cov(f,h)/Var(h)c^* = \mathrm{Cov}(f, h)/\mathrm{Var}(h) the variance is σf2−Cov2/σh2=σf2(1−ρ2)\sigma_f^2 - \mathrm{Cov}^2/\sigma_h^2 = \sigma_f^2(1 - \rho^2): the residual of a regression of ff on hh.

5. r squared. b=Sxy/Sxxb = S_{xy}/S_{xx} and b′=Sxy/Syyb' = S_{xy}/S_{yy}, so bb′=Sxy2/(SxxSyy)=r2b b' = S_{xy}^2/(S_{xx}S_{yy}) = r^2. The two lines coincide only when ∣r∣=1|r| = 1.

6. That input's share of the output variance. With y≈∑ikixiy \approx \sum_i k_i x_i and independent inputs, Var y=∑iki2σi2\mathrm{Var}\,y = \sum_i k_i^2 \sigma_i^2 and ri2=ki2σi2/Var yr_i^2 = k_i^2\sigma_i^2/\mathrm{Var}\,y.

Keep these:

  1. An integral is an expectation; the sample mean estimates it with SE=σ/N\mathrm{SE} = \sigma/\sqrt N, order 12\tfrac12 in NN.
  2. That rate does not depend on dimension; a product rule's N−2/dN^{-2/d} does, so past d=4d = 4 sampling wins. The constant σd\sigma_d may still grow.
  3. Estimate the bar with s/Ns/\sqrt N, report the seed with it, and remember the 95% is asymptotic: few or skewed samples cover less.
  4. Variance reduction changes the constant: a control variate leaves σ2(1−ρ2)\sigma^2(1-\rho^2); antithetic pairs need a monotone integrand.
  5. Least squares projects yy onto the columns of XX; the slope is a weighted average of slopes, b=rsy/sxb = r s_y/s_x, and bb′=r2b b' = r^2.
  6. A sensitivity study samples the inputs and reads the output's spread; the regression slope is the sensitivity and r2r^2 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. 1.96×2.0/100=0.03921.96 \times 2.0/100 = 0.0392.

Practice B. 80 00080\,000, since the error falls by 4 and NN rises by 16.

Practice C. 1/(1−0.952)≈10.31/(1-0.95^2) \approx 10.3.

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

§3 Error bars, coverage and seeds

§4 Variance reduction

§5 Regression as averaging


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

Settings

Colour scheme

Light or dark pages. Your colour and layout stay the same.

Colour

The paper, ink and lettering. Your layout stays the same.

Quiet colours
Bold colours
Reading offline

Keep this book on this device and read it offline.