Bootstrap a 95% confidence interval for the median order value
values is a list of order amounts. Return a 95% confidence interval (low, high) for the median using the percentile bootstrap — the median has no simple closed-form standard error, so resampling is the natural tool.
Use n_boot resamples and a fixed seed so the result is reproducible.
def bootstrap_median_ci(values: list[float], n_boot: int = 10000,
seed: int = 0) -> tuple[float, float]:
# your code here
Write the implementation.
Resample the values with replacement to size n, take each resample's median, and repeat a few thousand times. The 2.5th and 97.5th percentiles of those bootstrap medians are the 95% CI — no closed-form standard error required.
- ✗Resampling without replacement or at the wrong size
- ✗Applying a normal-approximation formula to the median
- ✗Percentile-ing the raw values instead of the bootstrap medians
- →Why resample to exactly n rather than some smaller size?
- →How would the interval change if you doubled n_boot?
Draw n_boot resamples of size n with replacement, record each median, then read off the 2.5% and 97.5% percentiles of the sorted bootstrap medians.
import random
from statistics import median
def bootstrap_median_ci(values, n_boot=10000, seed=0):
rng = random.Random(seed)
n = len(values)
boot = []
for _ in range(n_boot):
sample = [values[rng.randrange(n)] for _ in range(n)]
boot.append(median(sample))
boot.sort()
lo = boot[int(0.025 * n_boot)]
hi = boot[int(0.975 * n_boot)]
return (lo, hi)
The two ideas that make it correct: resample with replacement to the same size n (so each resample mimics a fresh draw from the population), and take percentiles of the statistic — the medians — not of the raw order values.