Nonparametric

The bootstrap

To see how much a statistic would vary from sample to sample, resample the sample: draw n values with replacement, recompute, and repeat. For a small sample every resample can be listed and weighed, so the bootstrap distribution is exact; otherwise it is simulated from a seed.

Exact, for small samples

import { bootstrap } from "@ratmath/stats";

const b = bootstrap([1, 2, 3, 4, 10]);
String(b);       // "mean 4; bootstrap se 1.41421, bias 0; percentile 0.950 interval [1.80000, 7.20000]
                 //  (exact over 126 distinct resamples)"
b.variance;      // 2: the plug-in variance 10 divided by n = 5
b.interval;      // { low: 9/5, high: 36/5, level: 19/20 }
b.distribution;  // every value the mean can take (39 of them), with its exact probability

A resample is a multiset of size nn from the nn data points: there are (2n−1n)\binom{2n-1}{n} of them, and the one that uses point ii exactly cic_i times has probability

n!c1!⋯cn!  nn. \frac{n!}{c_1!\cdots c_n!\; n^n}.

When there are at most 20,000 (n≤9n \le 9), all of them are weighed and the bootstrap mean, variance, bias and quantiles are exact fractions. This is the bootstrap distribution itself, the thing a simulation only estimates, and it shows the method's own answer without simulation noise. For the mean it reproduces the plug-in formula σ^2/n\hat\sigma^2/n exactly.

Simulated, from a seed

const data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9];
String(bootstrap(data, "median"));
// "median 5; bootstrap se 1.076, bias -0.0145; percentile 0.950 interval [3, 7] (simulated: 2000 resamples, seed 1)"
bootstrap(data, "median", { method: "basic" }).interval;   // [3, 7]: 2·5 − 7 and 2·5 − 3
bootstrap(data, (xs) => Math.max(...xs.map(Number)), { resamples: 5000, seed: "max" });

The statistic is "mean", "median", "variance" or any function of the resampled list. The percentile interval takes the α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles of the replicates θ^∗\hat\theta^*; the basic interval reflects them about the estimate, [2θ^−q1−α/2, 2θ^−qα/2][2\hat\theta - q_{1-\alpha/2},\, 2\hat\theta - q_{\alpha/2}]. Both are approximations whose coverage depends on the statistic and the sample size; for the median of small samples the bootstrap distribution is lumpy, as the exact version shows. Testing the tests shows how to check coverage with a seeded experiment.

Try itEdit the code and run it with @ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs