Skip to content

13.5 LLN, CLT, confidence intervals, bootstrap

Sooner or later every model builder has to compare two models. In AI Engineering, the RNN language model reports a bits-per-character number and the encoder-decoder model a BLEU score from Sequence metrics, and the question is never “what is the number” but “is model A better than model B, or did I get a lucky test set”. A BLEU of 21.3 against 20.8 on 200 sentences means nothing until you know how much BLEU moves when you draw another 200 sentences.

Concepts from other sections (12)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

From that point on, every metric the books print carries a 95% interval: sequence metrics, the LM evaluation harness, the verdicts of Quantization. The comparison tests of the next section, Hypothesis tests, build on the same machinery. This section gives that interval three ways: from a formula for means, from a formula for proportions, and by resampling for everything else. Along the way you will implement the normal and Student’s tt CDFs and quantiles from first principles.

No code from earlier sections is needed. The reading background is expectation, variance, and the normal from Random variables, expectation, variance, and normal draws, the one-uniform-per-draw discipline of Categorical sampling, and the variance of a sum from problem set B. The reference implementation is course/solutions/python/tinyllm/prob/stats.py, with its contract in stats.pyi; the generator behind rng is specified in spec/pcg32.md.

Learning objectives

  • State the law of large numbers and the central limit theorem, and use them to explain why error bars shrink as 1/n1/\sqrt{n}.
  • Build a tt interval for a mean, and explain why Bessel’s n−1n - 1, the tt quantile, and α/2\alpha/2 are each required.
  • Compute the normal and tt quantiles by bisection on their CDFs.
  • Compute a Wilson interval for a proportion and explain where the Wald interval fails.
  • Implement a reproducible percentile bootstrap with a fixed index rule and type 7 quantiles.
SymbolMeaningType / shape
X1,…,XnX_1, \dots, X_nindependent draws from one distribution (per-example scores)reals
μ,σ2\mu, \sigma^2the true mean and variance of that distributionreals
Xˉn=1n∑iXi\bar X_n = \frac{1}{n}\sum_i X_ithe sample meanreal
s2=1n−1∑i(Xi−Xˉn)2s^2 = \frac{1}{n-1}\sum_i (X_i - \bar X_n)^2the sample variance (Bessel’s n−1n - 1)real
se=s/n\mathrm{se} = s/\sqrt{n}the standard error: estimated sd of Xˉn\bar X_nreal
α\alphathe miss rate; 1−α1 - \alpha is the confidence level (0.95)real in (0,1)(0, 1)
Φ(z)\Phi(z), Φ−1(p)\Phi^{-1}(p)the standard normal CDF and its quantilefunctions
tνt_\nu, Fν(t)F_\nu(t), Fν−1(p)F_\nu^{-1}(p)Student’s t with ν\nu degrees of freedom, its CDF and quantilefunctions
k,n,p^=k/nk, n, \hat p = k/nsuccesses, trials, observed proportionintegers, real
BB, θb∗\theta^*_bnumber of bootstrap resamples, the statistic on resample bbinteger, reals

By linearity E[Xˉn]=μE[\bar X_n] = \mu, and because independent variances add, Var⁡(Xˉn)=nσ2/n2=σ2/n\operatorname{Var}(\bar X_n) = n\sigma^2/n^2 = \sigma^2/n (question 3 of problem set B, with all covariances 0). Chebyshev’s inequality then gives P(∣Xˉn−μ∣≥ε)≤σ2/(nε2)→0P(|\bar X_n - \mu| \ge \varepsilon) \le \sigma^2/(n\varepsilon^2) \to 0: the mean of more data is closer to the truth (proved in question 5 of problem set C). It also gives the rate: the typical error is σ/n\sigma/\sqrt{n}, so four times the eval set halves the error, it does not quarter it.

The law of large numbers says the error shrinks; the central limit theorem says what shape it has. Whatever the distribution of each XiX_i (finite variance is all it needs), the standardized mean n(Xˉn−μ)/σ\sqrt{n}(\bar X_n - \mu)/\sigma tends to the standard normal N(0,1)\mathcal{N}(0, 1). So P(∣Xˉn−μ∣≤z σ/n)≈2Φ(z)−1P(|\bar X_n - \mu| \le z\,\sigma/\sqrt{n}) \approx 2\Phi(z) - 1, and choosing z=Φ−1(1−α/2)z = \Phi^{-1}(1 - \alpha/2) (1.96 for 95%) turns that into an interval: Xˉn±z σ/n\bar X_n \pm z\,\sigma/\sqrt{n} covers μ\mu in about 1−α1 - \alpha of repeated samples. Per-example eval scores are never normal (0/1 accuracy, skewed losses), and the interval still works once nn is in the hundreds: that is the CLT.

To use the interval you need Φ\Phi and its inverse. Φ(z)=12erfc⁡(−z/2)\Phi(z) = \frac{1}{2}\operatorname{erfc}(-z/\sqrt{2}), with math.erfc (it keeps full relative precision in the lower tail, where 1−Φ1 - \Phi computed by subtraction would lose every digit). The quantile Φ−1(p)\Phi^{-1}(p) has no closed form, but Φ\Phi is increasing, so bisection finds it: keep a bracket [l,h][l, h] with Φ(l)<p≤Φ(h)\Phi(l) < p \le \Phi(h) and halve it until the midpoint equals an end, which is the last bit of a double. For p>1/2p > 1/2 use the symmetry Φ−1(p)=−Φ−1(1−p)\Phi^{-1}(p) = -\Phi^{-1}(1 - p); 1−p1 - p is exact in float64 there.

The interval above needs σ\sigma, and you only have ss, computed from the same data. The ratio T=(Xˉn−μ)/(s/n)T = (\bar X_n - \mu)/(s/\sqrt{n}) is wider-tailed than the normal (when ss happens to be small, TT is large), and for normal data it follows Student’s t with ν=n−1\nu = n - 1 degrees of freedom exactly (Gosset, 1908). So the interval is

Xˉn±Fn−1−1(1−α/2) sn.\bar X_n \pm F_{n-1}^{-1}(1 - \alpha/2)\,\frac{s}{\sqrt{n}}.

Two details carry it. The first is the n−1n - 1 in s2s^2: the deviations are measured from Xˉn\bar X_n, which sits closer to the data than μ\mu does, so dividing by nn underestimates σ2\sigma^2. The second is α/2\alpha/2: the interval misses on both sides. At n=10n = 10 the normal quantile covers only about 92% instead of 95%.

For integer ν\nu the CDF has a closed form (Abramowitz and Stegun 26.7.3 and 26.7.4). With θ=arctan⁡(∣t∣/ν)\theta = \arctan(|t|/\sqrt{\nu}) and A=P(∣T∣<∣t∣)A = P(|T| < |t|):

  • ν\nu even: A=sin⁡θ (1+12cos⁡2θ+1⋅32⋅4cos⁡4θ+⋯+1⋅3⋯(ν−3)2⋅4⋯(ν−2)cos⁡ν−2θ)A = \sin\theta\,\bigl(1 + \tfrac{1}{2}\cos^2\theta + \tfrac{1 \cdot 3}{2 \cdot 4}\cos^4\theta + \dots + \tfrac{1 \cdot 3 \cdots (\nu-3)}{2 \cdot 4 \cdots (\nu-2)}\cos^{\nu-2}\theta\bigr),
  • ν\nu odd: A=2π(θ+sin⁡θ (cos⁡θ+23cos⁡3θ+⋯+2⋅4⋯(ν−3)1⋅3⋯(ν−2)cos⁡ν−2θ))A = \tfrac{2}{\pi}\bigl(\theta + \sin\theta\,(\cos\theta + \tfrac{2}{3}\cos^3\theta + \dots + \tfrac{2 \cdot 4 \cdots (\nu-3)}{1 \cdot 3 \cdots (\nu-2)}\cos^{\nu-2}\theta)\bigr), just 2θ/π2\theta/\pi for ν=1\nu = 1,

and Fν(t)=12+12sign⁡(t) AF_\nu(t) = \tfrac{1}{2} + \tfrac{1}{2}\operatorname{sign}(t)\,A. Each term is the previous one times a ratio (2k−12kcos⁡2θ\tfrac{2k-1}{2k}\cos^2\theta or 2k2k+1cos⁡2θ\tfrac{2k}{2k+1}\cos^2\theta), so a cumulative product computes the series in O(ν)O(\nu). The quantile is bisection again, on a bracket [0,b][0, b] whose top doubles until Fν(b)≥pF_\nu(b) \ge p (ν=1\nu = 1 needs t=636.6t = 636.6 at p=0.9995p = 0.9995, so no fixed bound is safe). As ν\nu grows, tνt_\nu tends to the normal: F1000−1(0.975)=1.9623F_{1000}^{-1}(0.975) = 1.9623 against 1.96001.9600.

An accuracy is a mean of 0/1 values, so you might expect the mean interval to serve. But the formula p^±zp^(1−p^)/n\hat p \pm z\sqrt{\hat p(1-\hat p)/n} (the Wald interval) fails exactly where safety evals live: with 0 failures in 10 trials it says [0,0][0, 0], certainty. Wilson (1927) inverts the test instead: the interval is every pp with ∣p^−p∣≤zp(1−p)/n|\hat p - p| \le z\sqrt{p(1-p)/n}. Squaring and solving the quadratic in pp gives

p^+z22n±zp^(1−p^)n+z24n21+z2n,\frac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}},

whose center is pulled toward 1/21/2 and which is never empty. At k=0k = 0 its lower end is exactly 0 and at k=nk = n its upper end exactly 1; rounding can leave them a hair off, so the code pins them.

Means and proportions have formulas. Many metrics do not. For a statistic with no variance formula (BLEU, chrF, a median, pass@k), Efron’s idea (1979) is to let the data stand in for the population: draw nn indices with replacement, recompute the statistic on that resample, repeat BB times, and read the spread of θ1∗,…,θB∗\theta^*_1, \dots, \theta^*_B. The percentile interval is their α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles.

Two rules make it reproducible across languages (the Go evaluation harness of Paired A/B experiments, in AI Engineering, reimplements it). Each index is i=min⁡(⌊un⌋,n−1)i = \min(\lfloor u n \rfloor, n - 1) from exactly one rng.uniform(), drawn in order (resample 0’s indices first). And the quantile is type 7: sort, h=(B−1)qh = (B-1)q, i=⌊h⌋i = \lfloor h \rfloor, value si+(h−i)(si+1−si)s_i + (h - i)(s_{i+1} - s_i) (numpy’s default). The point estimate stays θ(x)\theta(x) on the original data.

A t interval. Take x=[2,4,4,5,7,8]x = [2, 4, 4, 5, 7, 8], n=6n = 6.

  1. Mean: 30/6=530/6 = 5.
  2. Deviations: −3,−1,−1,0,2,3-3, -1, -1, 0, 2, 3; squares sum to 9+1+1+0+4+9=249 + 1 + 1 + 0 + 4 + 9 = 24.
  3. s2=24/(6−1)=4.8s^2 = 24/(6 - 1) = 4.8, s=2.19089s = 2.19089; se=4.8/6=0.8=0.894427\mathrm{se} = \sqrt{4.8/6} = \sqrt{0.8} = 0.894427.
  4. ν=5\nu = 5, 1−α/2=0.9751 - \alpha/2 = 0.975: F5−1(0.975)=2.570582F_5^{-1}(0.975) = 2.570582 (bisection on the odd series, which for ν=5\nu = 5 is θ+sin⁡θ(cos⁡θ+23cos⁡3θ)\theta + \sin\theta(\cos\theta + \frac{2}{3}\cos^3\theta)).
  5. Half-width 2.570582×0.894427=2.2991982.570582 \times 0.894427 = 2.299198; interval [2.700802,7.299198][2.700802, 7.299198].

With the normal 1.959964 instead, the interval would be [3.246955,6.753045][3.246955, 6.753045], a quarter narrower: at n=6n = 6 that is a large overstatement of certainty.

One value of the series. F3(1)F_3(1): θ=arctan⁡(1/3)=π/6\theta = \arctan(1/\sqrt{3}) = \pi/6, sin⁡θ=1/2\sin\theta = 1/2, cos⁡θ=3/2\cos\theta = \sqrt{3}/2. The odd series with ν=3\nu = 3 stops after cos⁡θ\cos\theta: A=2π(π6+12⋅32)=13+32π=0.608998A = \frac{2}{\pi}(\frac{\pi}{6} + \frac{1}{2}\cdot\frac{\sqrt{3}}{2}) = \frac{1}{3} + \frac{\sqrt{3}}{2\pi} = 0.608998, so F3(1)=12+12A=0.804499F_3(1) = \frac{1}{2} + \frac{1}{2}A = 0.804499.

A Wilson interval. k=0k = 0, n=10n = 10, z=1.959964z = 1.959964, z2=3.841459z^2 = 3.841459: 1+z2/n=1.3841461 + z^2/n = 1.384146, center =(0+0.192073)/1.384146=0.138766= (0 + 0.192073)/1.384146 = 0.138766, half-width =1.959964×0+3.841459/400/1.384146=0.138766= 1.959964 \times \sqrt{0 + 3.841459/400}/1.384146 = 0.138766. The interval is [0,0.277533][0, 0.277533]; the Wald interval is [0,0][0, 0].

These are the first two test cases a correct implementation must reproduce.

Nine functions cover the distributions, the two formula intervals, and the bootstrap:

python/tinyllm/prob/stats.py
def normal_cdf(z: float) -> float
def normal_ppf(p: float) -> float # bisection, symmetric for p > 1/2
def t_cdf(t: float, df: int) -> float # A&S 26.7.3 / 26.7.4
def t_ppf(p: float, df: int) -> float # bracket doubled, then bisection
def standard_error(x) -> float # s / sqrt(n), divisor n - 1
def mean_ci(x, alpha: float = 0.05) -> tuple[float, float, float] # (mean, lo, hi)
def wilson_interval(k: int, n: int, alpha: float = 0.05) -> tuple[float, float]
def quantile(x, q: float) -> float # type 7
def bootstrap_ci(x, stat, n_boot: int, alpha: float, rng) -> tuple[float, float, float] # (stat(x), lo, hi)

Seven decisions produce the implementation.

  1. Every quantile is the inverse of an increasing CDF, so one bisection serves them all. Keep f(lo)<target≤f(hi)f(\mathit{lo}) < \mathit{target} \le f(\mathit{hi}) and halve until the midpoint equals an end: that is the last bit of a double, about 60 halvings, with no tolerance to choose.
  2. Φ\Phi from erfc, and the upper half by symmetry. Φ(z)=12erfc⁡(−z/2)\Phi(z) = \tfrac12\operatorname{erfc}(-z/\sqrt2) keeps relative precision in the lower tail. For p>12p > \tfrac12, 1−p1 - p is exact (Sterbenz), so Φ−1(p)=−Φ−1(1−p)\Phi^{-1}(p) = -\Phi^{-1}(1-p) never bisects in the region where Φ\Phi is flat near 1.
  3. The tt CDF from the finite series. For integer ν\nu, A&S 26.7.3/4 give P(∣T∣<∣t∣)P(|T| < |t|) in O(ν)O(\nu) terms, each the previous times a ratio, so a cumulative product computes them. The quantile needs a bracket that grows with the tail: double hi until Fν(hi)≥pF_\nu(\mathit{hi}) \ge p, then bisect.
  4. The standard error uses Bessel and n\sqrt n. s2=∑(xi−xˉ)2/(n−1)s^2 = \sum (x_i - \bar x)^2/(n-1), then s/ns/\sqrt n. Two passes, as in the variance of the first section, so a large mean does not cancel.
  5. The mean interval is xˉ±Fn−1−1(1−α/2)⋅se\bar x \pm F^{-1}_{n-1}(1 - \alpha/2)\cdot\mathrm{se}. Both the tt (estimated σ\sigma) and the α/2\alpha/2 (two-sided) are required for the promised coverage.
  6. Wilson is the closed form of an inverted test, with pinned ends. Compute center and half-width from the formula; set the lower end to exactly 0 when k=0k = 0 and the upper to exactly 1 when k=nk = n, and clamp otherwise.
  7. The bootstrap is reproducible only with a fixed draw rule. Index min⁡(⌊un⌋,n−1)\min(\lfloor un \rfloor, n-1) from one uniform, resample by resample, row by row; the interval is the type 7 quantiles of the replicates; the point estimate is the statistic on the original data.

The bisection helper and the normal distribution come first:

def _bisect(f: Callable[[float], float], target: float, lo: float, hi: float) -> float:
"""The x in [lo, hi] where the increasing f crosses target, to the last bit:
keeps f(lo) < target <= f(hi) and halves until the midpoint is an end."""
for _ in range(2000): # a safety cap; ~60-1100 halvings reach adjacent doubles
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi: # lo and hi are neighbouring floats: done
break
if f(mid) < target:
lo = mid
else:
hi = mid
return hi # the smallest x found with f(x) >= target
def normal_cdf(z: float) -> float:
return 0.5 * math.erfc(-float(z) / math.sqrt(2.0)) # no 1 - (...) subtraction in the lower tail
def normal_ppf(p: float) -> float:
p = float(p)
if not 0.0 < p < 1.0:
raise ValueError(f"normal_ppf needs 0 < p < 1, got {p!r}")
if p == 0.5:
return 0.0
if p > 0.5:
# 1 - p is exact for p in [0.5, 1) (Sterbenz), so the upper tail keeps
# its precision by symmetry.
return -normal_ppf(1.0 - p)
return _bisect(normal_cdf, p, -40.0, 0.0) # Phi(-40) underflows to 0, below any p > 0

The loop stops on floats, not on a tolerance, so the answer is as close as float64 allows whatever the scale of xx; the 2000 cap only guards against a non-terminating f.

Student’s tt follows the series term by term:

def _t_abs_prob(t: float, df: int) -> float:
"""A = P(|T| < |t|) by Abramowitz and Stegun 26.7.3 (odd df) and 26.7.4 (even df)."""
theta = math.atan(abs(t) / math.sqrt(df))
s, c = math.sin(theta), math.cos(theta)
c2 = c * c
if df % 2 == 0:
# 1 + (1/2) c^2 + (1 3)/(2 4) c^4 + ... : k-th ratio (2k - 1) / (2k) c^2
m = (df - 2) // 2
if m == 0:
return s # df = 2: A = sin(theta)
k = np.arange(1, m + 1, dtype=np.float64)
terms = np.cumprod((2.0 * k - 1.0) / (2.0 * k) * c2)
return s * (1.0 + float(np.sum(terms)))
if df == 1:
return 2.0 * theta / math.pi # Cauchy
# c + (2/3) c^3 + (2 4)/(3 5) c^5 + ... : k-th ratio (2k) / (2k + 1) c^2
m = (df - 3) // 2
k = np.arange(1, m + 1, dtype=np.float64)
terms = c * np.cumprod((2.0 * k) / (2.0 * k + 1.0) * c2) if m else np.zeros(0)
return 2.0 / math.pi * (theta + s * (c + float(np.sum(terms))))
def t_cdf(t: float, df: int) -> float:
df = _check_df(df) # an integer >= 1
t = float(t)
if math.isnan(t):
raise ValueError("t_cdf of NaN")
if math.isinf(t):
return 1.0 if t > 0 else 0.0
a = _t_abs_prob(t, df)
return 0.5 + 0.5 * a if t >= 0 else 0.5 - 0.5 * a # F = 1/2 + sign(t) A / 2
def t_ppf(p: float, df: int) -> float:
# (argument checks elided)
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, df) # symmetry
hi = 1.0
while t_cdf(hi, df) < p: # no fixed bound is safe: nu = 1 needs 636.6 at 0.9995
hi *= 2.0
return _bisect(lambda v: t_cdf(v, df), p, 0.0, hi)

Checking the hand value F3(1)F_3(1): θ=π/6\theta = \pi/6, m = 0, so terms is empty and the odd branch returns 2π(π6+12⋅32)=0.608998\frac{2}{\pi}(\frac{\pi}{6} + \frac12 \cdot \frac{\sqrt3}{2}) = 0.608998; t_cdf gives 0.8044990.804499.

With the quantiles in place, the mean interval is short:

def standard_error(x: ArrayLike) -> float:
a = _sample(x, 2) # 1-D, finite, at least 2 values
n = a.size
mean = math.fsum(a.tolist()) / n
ss = math.fsum(((a - mean) ** 2).tolist()) # two passes: centre, then square
# Bessel: the deviations are measured from the sample mean, which sits
# closer to the data than mu does, so divide by n - 1, not n.
return math.sqrt(ss / (n - 1)) / math.sqrt(n)
def mean_ci(x: ArrayLike, alpha: float = 0.05) -> tuple[float, float, float]:
a = _sample(x, 2)
alpha = _check_alpha(alpha)
mean = math.fsum(a.tolist()) / a.size
half = t_ppf(1.0 - alpha / 2.0, a.size - 1) * standard_error(a) # t with n - 1 df, two-sided
return mean, mean - half, mean + half

On [2,4,4,5,7,8][2, 4, 4, 5, 7, 8]: ss = 24, se=4.8/6=0.8\mathrm{se} = \sqrt{4.8}/\sqrt6 = \sqrt{0.8}, t_ppf(0.975, 5) = 2.570582, half-width 2.2991982.299198.

The Wilson interval is the closed form plus the pinned ends:

def wilson_interval(k: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
# (integer and range checks elided: 0 <= k <= n, n >= 1)
z = normal_ppf(1.0 - _check_alpha(alpha) / 2.0)
z2 = z * z
phat = k / n
denom = 1.0 + z2 / n
center = (phat + z2 / (2.0 * n)) / denom # pulled toward 1/2
half = z * math.sqrt(phat * (1.0 - phat) / n + z2 / (4.0 * n * n)) / denom # never 0
# In exact arithmetic the interval ends at 0 when k = 0 and at 1 when
# k = n; rounding can leave it a hair inside or outside, so pin the ends.
lo = 0.0 if k == 0 else max(0.0, center - half)
hi = 1.0 if k == n else min(1.0, center + half)
return lo, hi

Finally, the type 7 quantile and the bootstrap that uses it:

def quantile(x: ArrayLike, q: float) -> float:
# (empty, NaN, and q range checks elided)
s = np.sort(a)
h = (s.size - 1) * q # type 7: position on 0 .. n - 1
i = int(math.floor(h))
if i >= s.size - 1:
return float(s[-1]) # q = 1 (or one value): no s[i + 1] to read
return float(s[i] + (h - i) * (s[i + 1] - s[i])) # linear interpolation
def bootstrap_ci(x, stat, n_boot: int, alpha: float, rng) -> tuple[float, float, float]:
a = _sample(x, 1)
alpha = _check_alpha(alpha)
# (n_boot check elided: an integer >= 1)
n = a.size
thetas = np.empty(int(n_boot), dtype=np.float64)
for b in range(int(n_boot)):
idx = np.empty(n, dtype=np.int64) # a fresh resample every replicate
for i in range(n):
# One uniform per index, in order: the same seed resamples the same
# rows in Python and in Go (ag.12).
idx[i] = min(int(rng.uniform() * n), n - 1) # floor, clamped against rounding
thetas[b] = float(stat(a[idx]))
return (
float(stat(a)), # the point estimate is on the original data
quantile(thetas, alpha / 2.0),
quantile(thetas, 1.0 - alpha / 2.0),
)

The index rule is worth checking on a boundary case. With u=0.74u = 0.74 and n=4n = 4, the floor gives ⌊2.96⌋=2\lfloor 2.96 \rfloor = 2; rounding would give 3. Rounding gives index 0 only the uniforms below 0.1250.125 and pushes the top eighth onto the last index, so the rows stop being equally likely; the floor gives each row exactly a quarter of [0,1)[0, 1). The full solution is stats.py.

Φ−1\Phi^{-1} costs about 60 to 1100 erfc calls (the bracket starts at −40-40 and halves to adjacent doubles); Fν−1F_\nu^{-1} is O(log⁡hi)O(\log \mathit{hi}) doublings plus a bisection, each step O(ν)O(\nu). The bootstrap is B⋅nB \cdot n uniforms plus BB calls to stat, and the quantiles sort BB values: O(Bn+Blog⁡B)O(Bn + B\log B) plus the statistic’s cost.

Bisection is chosen over rational approximations. scipy’s Cephes uses rational approximations with Newton polishing, which is faster but hard to verify and to port. Bisection on a correct CDF is obviously correct, ends at the last bit, and gives the Go port a definition it can reproduce exactly.

The tt quantile beats the normal and Wilson beats Wald for the same reason: both alternatives are simpler and both fail where evaluation lives, at small nn (the normal covers 92% at n=10n = 10) and for proportions near 0 or 1 (Wald says [0,0][0, 0]). Wilson costs one more square root.

The percentile bootstrap is chosen over BCa. BCa corrects bias and skew and has better coverage for skewed statistics, but needs a jackknife pass and more code to port. The percentile interval is what the Go harness reimplements and is adequate for metric reporting.

The tradeoff accepted is speed: the scalar Python loops are slow for large BnB n (a few seconds at B=1000B = 1000, n=1000n = 1000). Vectorized resampling would draw the same uniforms but obscure the one-uniform-per-index rule that makes cross-language reproduction possible.

A correct solution reproduces the hand values, matches scipy and numpy, achieves its promised coverage, and handles the boundaries. The full list:

CaseKind of checkChecksWhy it matters downstream
the tt interval by handunitse =0.8= \sqrt{0.8}, interval [2.700802,7.299198][2.700802, 7.299198], F3(1)=0.804499F_3(1) = 0.804499everyone agrees on Bessel, α/2\alpha/2, and tt
the Wilson interval by handunit[0,0.277533][0, 0.277533] at k=0k = 0safety failure rates (Bias and safety evals)
the normal against scipygoldenΦ\Phi and Φ−1\Phi^{-1} to 1e-11 relative, tails to p=10−12p = 10^{-12}every zz in the books
Student’s tt against scipygoldenFνF_\nu and Fν−1F_\nu^{-1} for 13 values of ν\nu from 1 to 1000small eval sets get the right width
mean_ci against scipygoldenstandard_error and mean_ci equal scipy.stats.sem and t.intervalevaluation harness reports
Wilson against scipygoldenscipy’s Wilson interval at the extremes and in the middleaccuracy CIs
type 7 quantilesgoldenequal to numpy’s defaultGo’s bootstrap agrees
an independent bootstrapgoldensame seed, same interval as an independent implementation, mean and medianreproducible CIs for BLEU
coverage at small nnstatistical2000 samples of n=10n = 10: coverage in [0.93,0.97][0.93, 0.97]what “95%” promises
coverage on skewed datastatisticalexponential data, n=200n = 200: coverage in [0.93,0.97][0.93, 0.97]the CLT on non-normal scores
the n\sqrt{n} lawpropertyfour copies of the data halve the standard errorsizing eval sets
quantile consistencypropertyF(F−1(p))=pF(F^{-1}(p)) = p, symmetry, tν→t_\nu \to normalthe quantiles are consistent
tt closed formsunitν=1\nu = 1 (Cauchy) and ν=2\nu = 2 closed formsboth series are right at their shortest
bootstrap draws and determinismunitBnB n uniforms; same seed same result; point is θ(x)\theta(x)cross-language reproducibility
the bootstrap index ruleboundaryu=0.74u = 0.74, n=4n = 4 is index 2, u→1u \to 1 is the last indexthe floor rule
shift equivariancepropertyx+cx + c moves the mean’s interval by ccresampling does not look at values
quantile edgesboundaryq=0q = 0, q=1q = 1, one value, unsorted inputno index past the end
Wilson inside [0,1][0, 1]boundaryexact 0 and 1 at the ends; p^\hat p insideintervals stay probabilities
bad argumentsboundaryn<2n < 2, α∉(0,1)\alpha \notin (0,1), k>nk > n, NaN, empty inputerrors at the call site

Every pitfall here produces an interval that looks reasonable and lies about its coverage, which is why they are worth knowing by name.

Warning: Three small slips each make intervals too narrow. Using the normal quantile with an estimated σ\sigma makes a “95%” interval cover 92% at n=10n = 10. Dividing by nn instead of n−1n - 1, or by nn instead of n\sqrt{n}, makes intervals too narrow by a little or by a lot. Taking the quantile at 1−α1 - \alpha instead of 1−α/21 - \alpha/2 produces a 90% interval labelled 95%.

The solution guards against all three with t_ppf(..., a.size - 1) in mean_ci, math.sqrt(ss / (n - 1)) / math.sqrt(n) in standard_error, and 1.0 - alpha / 2.0 in both mean_ci and wilson_interval.

For proportions, the Wald interval returns [0,0][0, 0] after zero failures, and unpinned Wilson ends can sit a hair outside [0,1][0, 1]; the solution uses Wilson’s closed form with lo = 0.0 if k == 0 and hi = 1.0 if k == n.

For the bootstrap, rounding unu n to pick an index draws the last row more often than the first and makes Go and Python disagree; the solution uses min(int(rng.uniform() * n), n - 1). Drawing one resample and reusing it makes every replicate identical, a zero-width interval; the solution builds a new idx inside the replicate loop.

Problem set C works the LLN proof, the CLT approximation, and these intervals by hand. Hypothesis tests builds permutation tests and McNemar on the same resampling. Across AI Engineering, Sequence metrics report BLEU and chrF with bootstrap intervals over sentences, every metric of the LM evaluation harness carries mean_ci or bootstrap_ci, Quantization asks whether a perplexity change is inside the noise, Serving metrics and tracing and GRPO with verifiable rewards are later call sites, and Multimodal eval metrics resamples items with bootstrap_ci for WER, VQA, caption, and zero-shot intervals. The Go evaluation harness of Paired A/B experiments reimplements bootstrap_ci from the same seed, and Bias and safety evals in AI Engineering reports safety failure rates with Wilson intervals.

  • Wasserman, All of Statistics, chapters 5 to 8 (convergence, the bootstrap).
  • Efron and Tibshirani, An Introduction to the Bootstrap (1993), chapter 13.
  • Brown, Cai, DasGupta, “Interval Estimation for a Binomial Proportion” (2001).
  • scipy’s stdtrit and ndtri (Cephes, scipy/special/cephes/stdtr.c, ndtri.c): rational approximations plus Newton steps, O(1)O(1) for any ν\nu.
  • scipy.stats.bootstrap (scipy/stats/_resampling.py): bias-corrected and accelerated (BCa) intervals, vectorized resampling.
  • statsmodels.stats.proportion.proportion_confint (statsmodels/stats/proportion.py): Agresti-Coull, Jeffreys, and Clopper-Pearson side by side.
  • HELM and lm-evaluation-harness standard errors (bootstrap_stderr in lm_eval/api/metrics.py): clustered standard errors when examples share a prompt.
  • Law of large numbers: the sample mean converges to the true mean as nn grows.
  • Central limit theorem: the standardized sample mean tends to N(0,1)\mathcal{N}(0, 1) for any distribution with finite variance.
  • Standard error: s/ns/\sqrt{n}, the estimated standard deviation of the sample mean.
  • Bessel’s correction: dividing the sum of squared deviations by n−1n - 1 rather than nn.
  • Student’s t distribution: the distribution of (Xˉ−μ)/(s/n)(\bar X - \mu)/(s/\sqrt n) for normal data, with n−1n - 1 degrees of freedom.
  • Wilson interval: a proportion interval obtained by inverting the normal test, never empty and always inside [0,1][0, 1].
  • Percentile bootstrap: an interval from the quantiles of a statistic recomputed on resamples drawn with replacement.
  • Type 7 quantile: linear interpolation at position (n−1)q(n-1)q of the sorted data, numpy’s default.
  • The law of large numbers says a sample mean converges to the true mean; the central limit theorem says the error is close to normal with standard deviation σ/n\sigma/\sqrt{n}, so quadrupling the data halves the error bar.
  • When σ\sigma is estimated from the same nn values, the right quantile is Student’s tt with n−1n - 1 degrees of freedom, not the normal one; at n=10n = 10 the normal quantile covers only about 92% instead of 95%.
  • Both quantiles come from bisection on a correct CDF, which ends at the last bit and ports exactly.
  • For a proportion near 0 or 1 the Wilson interval stays honest where the textbook p^±zp^(1−p^)/n\hat p \pm z\sqrt{\hat p(1-\hat p)/n} collapses to a point.
  • The percentile bootstrap gives an interval for any statistic, BLEU or a median included, by resampling the data; with one uniform per index it is reproducible across languages.
  1. Why does mean_ci use t_ppf(1 - alpha/2, n - 1) rather than normal_ppf(1 - alpha/2)?

    Answer

    The standard error uses ss, estimated from the same nn values. When ss is small by chance, (Xˉ−μ)/(s/n)(\bar X - \mu)/(s/\sqrt n) is large, so this ratio has heavier tails than the normal: Student’s tt with n−1n - 1 degrees of freedom. The normal quantile ignores that and covers only about 92% at n=10n = 10. As nn grows the two agree.

  2. Why does normal_ppf recurse on 1−p1 - p for p>12p > \tfrac12 instead of bisecting on [0,40][0, 40]?

    Answer

    Near the top Φ(z)\Phi(z) is within 10−1210^{-12} of 1, where float64 values are spaced 1.1×10−161.1 \times 10^{-16} apart, so bisecting against a target like 1−10−121 - 10^{-12} compares nearly equal numbers and loses digits. 1−p1 - p is computed exactly for p≥12p \ge \tfrac12, and the lower tail of Φ\Phi via erfc keeps full relative precision, so the symmetric problem is solved accurately.

  3. Why does t_ppf double hi in a loop instead of starting from a fixed bracket like [0,100][0, 100]?

    Answer

    The heavy tails of small ν\nu put the quantile far out: for ν=1\nu = 1 (Cauchy), F1−1(0.9995)=636.6F_1^{-1}(0.9995) = 636.6, and more extreme pp go further. Any fixed bound fails for some valid input. Doubling finds a valid upper end in O(log⁡t)O(\log t) steps for any ν\nu and pp.

  4. Why pin lo = 0.0 when k=0k = 0 in the Wilson interval, when the formula already gives 0?

    Answer

    It gives 0 in exact arithmetic: center and half-width are equal at k=0k = 0. In floating point they are computed by different operations and can differ in the last bit, leaving lo at ±10−17\pm 10^{-17}: a negative probability or an interval that excludes the observed p^=0\hat p = 0. Pinning restores the exact property.

  5. What goes wrong if bootstrap_ci draws the index array once and reuses it for every replicate?

    Answer

    Every replicate is the same resample, so all θb∗\theta^*_b are equal and the interval has zero width: the method reports certainty. The bootstrap’s spread comes from many independent resamples; each must draw nn fresh uniforms, BnBn in total.