flowchart TD
A["Observed sample"] --> B["Empirical distribution"]
B --> C["Draw n values with replacement"]
C --> D["Recompute statistic"]
D --> E["Collect B replicates"]
D --> C
E --> F["Estimate error or quantiles"]
12 Confidence intervals and the bootstrap
A point estimate is incomplete when we need to make a decision. If a sample’s average response time is 12 seconds, how precisely have we estimated the population average? An interval estimator attempts to communicate sampling uncertainty. Its interpretation depends on the framework used to construct it.
12.1 What confidence means
A \((1-\alpha)\) confidence procedure produces a random interval \(C(X)\) satisfying
\[ P_\theta(\theta\in C(X))\ge1-\alpha \]
for every \(\theta\) in the model, with the probability taken over the data-generation process. An exact procedure may attain equality, while approximate procedures target the coverage only asymptotically.
Once the data are observed, the interval is fixed and the frequentist parameter is fixed. The computed interval either contains the parameter or does not. A 95% confidence level does not assign a posterior probability of .95 to the particular interval. It says that the procedure would include the fixed parameter in at least 95% of repetitions under its conditions.
12.1.1 A pivot
A pivot is a function \(Q(X,\theta)\) whose sampling distribution is known and parameter-free. Choose constants \(a,b\) from that distribution so that \(P_\theta(a\le Q(X,\theta)\le b)=1-\alpha\). Solve both inequalities for \(\theta\) to construct the interval. This is a general method of obtaining exact coverage rather than guessing a distance around the estimate.
12.2 Normal-mean intervals
Assume iid \(X_i\sim N(\mu,\sigma^2)\) with known \(\sigma>0\). Since
\[ Z=\frac{\bar X-\mu}{\sigma/\sqrt n}\sim N(0,1), \]
let \(z=\Phi^{-1}(1-\alpha/2)\). The event \(-z\le Z\le z\) is equivalent to \(\bar X-z\sigma/\sqrt n\le\mu\le\bar X+z\sigma/\sqrt n\). Hence the exact equal-tail confidence interval is
\[ \boxed{\bar X\pm z_{1-\alpha/2}\frac{\sigma}{\sqrt n}}. \]
For 95% confidence, \(z_{.975}\approx1.96\).
When \(\sigma\) is unknown and the data are normal, Chapter 10 showed that the studentized mean is exactly \(t_{n-1}\). The same inversion, with the t quantile and observed standard deviation, produces
\[ \boxed{\bar X\pm t_{n-1,1-\alpha/2}\frac{S}{\sqrt n}}. \]
12.2.1 Example: processing time
Suppose \(n=16\) independent approximately normal processing times have sample mean \(12.4\) seconds and sample standard deviation \(2.0\) seconds. The estimated standard error is \(0.5\). With 15 degrees of freedom the 97.5th percentile of the t law is about \(2.131\), giving
\[ 12.4\pm2.131(0.5)=[11.3345,13.4655]. \]
The 95% interval is wider than it would be if \(\sigma=2.0\) were already known. Under exact normal sampling its coverage is exact. For nonnormal iid data with finite variance, studentization and the CLT justify the approximation for increasing \(n\), but a small sample with severe skewness need not behave well.
A confidence interval for \(\mu\) is not a prediction interval for an individual future processing time. Even with a huge sample, individual observations remain variable. For normal data a future prediction interval adds that observation’s own variance.
12.3 Intervals for a population variance
For iid normal observations, \(Q=(n-1)S^2/\sigma^2\sim\chi^2_{n-1}\). Denote chi-square quantiles by \(q_p\). Invert
\[ q_{\alpha/2}\le\frac{(n-1)S^2}{\sigma^2}\le q_{1-\alpha/2}. \]
Because all quantities are positive, taking reciprocals reverses inequalities:
\[ \left[ \frac{(n-1)S^2}{q_{1-\alpha/2}}, \frac{(n-1)S^2}{q_{\alpha/2}} \right]. \]
We obtain an interval for \(\sigma\) by taking square roots of the endpoints. Chi-square quantiles are asymmetric; replacing them with a symmetric error margin loses the exact derivation. This normal-theory interval can be sensitive to nonnormality.
12.4 Confidence intervals for a proportion
Let \(S\) be the number of successes in \(n\) independent Bernoulli trials, and \(\hat p=S/n\). The large-sample Wald interval is
\[ \hat p\pm z\sqrt{\frac{\hat p(1-\hat p)}{n}}. \]
It is easy to compute but may have poor coverage, particularly near \(p=0,1\) or with small \(n\). At \(S=0\) it degenerates to \([0,0]\). A more reliable large-sample approach is the Wilson score interval, obtained by inverting the approximate test of each candidate \(p\) using its null standard error:
\[ \frac{|\hat p-p|}{\sqrt{p(1-p)/n}}\le z. \]
Squaring and expanding yields the quadratic inequality
\[ (n+z^2)p^2-(2n\hat p+z^2)p+n\hat p^2\le0. \]
Its two roots delimit the allowed candidate values. Dividing the quadratic formula by \(n\) and simplifying gives the center and half-width:
\[ \boxed{ \frac{\hat p+z^2/(2n)}{1+z^2/n} \ \pm\ \frac{z}{1+z^2/n} \sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}} }. \]
The formula remains useful with zero successes (lower endpoint zero and positive upper endpoint). It is still an approximation, not an exact finite-sample guarantee. The Clopper–Pearson interval inverts exact binomial tail tests; because a binomial count is discrete, such intervals are typically conservative.
import numpy as np
from scipy import stats
s, n = 1, 20
phat = s/n
z = stats.norm.ppf(.975)
wald = phat+np.array([-1,1])*z*np.sqrt(phat*(1-phat)/n)
center = (phat+z*z/(2*n))/(1+z*z/n)
width = z*np.sqrt(phat*(1-phat)/n+z*z/(4*n*n))/(1+z*z/n)
wilson = center+np.array([-1,1])*width
exact = stats.binomtest(s,n).proportion_ci(confidence_level=.95)
print("Wald:", wald)
print("Wilson:", wilson)
print("Exact:", (exact.low,exact.high))Notice that the Wald interval has a negative lower endpoint here. A procedure can be computationally convenient yet unsuitable for a constrained parameter.
12.5 The nonparametric bootstrap
The bootstrap uses the observed sample as a discrete estimate of the population distribution. Let \(\widehat F_n\) assign mass \(1/n\) to every observed value (including multiplicities). Draw \(n\) independent values with replacement from \(\widehat F_n\), forming a bootstrap sample \(X^*\), and recompute \(T^*=T(X^*)\). Repeat independently \(B\) times conditionally on the original sample.
The conditional distribution of \(T^*\) approximates the sampling distribution of \(T\). More precisely, it is often the centered error \(T^*-T\) that approximates \(T-\theta\), under suitable regularity. For the mean, conditionally,
\[ E_*(\bar X^*)=\bar X,\qquad \operatorname{Var}_*(\bar X^*)=\frac{1}{n^2}\sum_i(x_i-\bar x)^2. \]
This is close to the usual estimate \(S^2/n\) at large \(n\), which helps explain why the bootstrap approximates the mean’s sampling variability.
Two common interval constructions are:
- Percentile: use the \(\alpha/2\) and \(1-\alpha/2\) empirical quantiles of the bootstrap estimates, \([q_{\alpha/2}^*,q_{1-\alpha/2}^*]\).
- Basic: invert the approximate centered-error distribution, \([2T-q_{1-\alpha/2}^*,2T-q_{\alpha/2}^*]\).
Both are approximate, and neither is guaranteed to be accurate for every statistic. The sample should adequately represent the population, and the ordinary iid bootstrap assumes independent observations. Time series may require block resampling; a maximum or extreme quantile may require specialized methods. Increasing \(B\) reduces simulation error but cannot repair an inadequate original sample.
12.5.1 Example: a median waiting time
import numpy as np
rng = np.random.default_rng(1200)
x = rng.exponential(5, 80)
b = 4000
idx = rng.integers(0, x.size, (b,x.size))
med = np.median(x)
boot = np.median(x[idx], axis=1)
q = np.quantile(boot,[.025,.975])
print("Median estimate:", med)
print("Percentile interval:", q)
print("Basic interval:", 2*med-q[::-1])
print("Bootstrap SE:", boot.std(ddof=1))The median estimator’s uncertainty is obtained without assuming normality of the waiting times. For this continuous model, the population median is \(5\log 2\), but in a real analysis that value would be unknown.
12.6 Precision and study size
In the known-variance normal-mean case, a target half-width \(h\) requires
\[ n\ge\left(\frac{z_{1-\alpha/2}\sigma}{h}\right)^2. \]
Round upward to an integer. If \(\sigma\) is unknown, use a justified planning estimate or a conservative bound. For a proportion, \(p(1-p)\le1/4\), so \(n\ge z^2/(4h^2)\) guarantees the Wald formula’s planned margin is at most \(h\), not that its exact coverage is guaranteed.
12.7 Practice problems
Work in your browser with Google Colab, or download the notebooks for Jupyter.
Practice notebook
Worked solutions
12.7.1 Exercise 1: An exact normal interval
A sample of 25 independent normal measurements has mean 47.2 and known population standard deviation 5. Construct a 95% confidence interval. What sample size would reduce the planned half-width to 0.5?
The standard error is \(5/\sqrt{25}=1\), so the interval is approximately \([45.24,49.16]\). For half-width 0.5 the requirement is \(n\ge(1.96\cdot5/0.5)^2=384.16\), giving 385.
12.7.2 Exercise 2: Invert a pivot
For a normal sample with \(n=10\) and \(s^2=4\), express a 90% interval for \(\sigma^2\) in terms of chi-square quantiles. Explain why the larger quantile goes into the lower endpoint.
The result is \([36/q_{.95},36/q_{.05}]\) with nine degrees of freedom. Inverting the positive pivot inequalities reverses their directions. The lower endpoint thus divides by the larger quantile.
12.7.3 Exercise 3: No observed successes
In 20 Bernoulli trials there are no successes. Derive the 95% Wilson interval from the quadratic. Compare to the Wald interval.
Substitute \(\hat p=0\) to obtain \((n+z^2)p^2-z^2p\le0\), so the allowed range is \([0,z^2/(n+z^2)]\approx[0,0.161]\). The Wald interval is \([0,0]\) and cannot plausibly capture a small positive unknown proportion.
12.7.4 Exercise 4: Measure confidence coverage (Python)
Generate 20,000 samples of size twelve from \(N(5,2^2)\). Construct the 95% t interval in each sample. Compare the empirical coverage and average length with a naive interval that substitutes \(S\) but uses 1.96 rather than the t critical value.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1201)
n = 12
x = rng.normal(5,2,(20_000,n))
m = x.mean(axis=1)
se = x.std(axis=1,ddof=1)/np.sqrt(n)
for label,c in [("t",stats.t.ppf(.975,n-1)),("naive z",stats.norm.ppf(.975))]:
h = c*se
covered = abs(m-5)<=h
print(label, "coverage",covered.mean(),"mean length",(2*h).mean())
if label=="t":
assert abs(covered.mean()-.95)<.01The t procedure targets the exact .95 coverage. The naive z interval is shorter and undercovers, because it neglects uncertainty in the estimated standard deviation.
12.7.5 Exercise 5: Compare proportion intervals (Python)
For \(n=20\) and each true \(p\) in \((.02,.05,.2,.5)\), enumerate all possible binomial counts and calculate the exact coverage of the 95% Wald and Wilson procedures. Explain why simulated counts are unnecessary here.
import numpy as np
from scipy import stats
n = 20
k = np.arange(n+1)
ph = k/n
z = stats.norm.ppf(.975)
wh = z*np.sqrt(ph*(1-ph)/n)
c = (ph+z*z/(2*n))/(1+z*z/n)
h = z*np.sqrt(ph*(1-ph)/n+z*z/(4*n*n))/(1+z*z/n)
for p in [.02,.05,.2,.5]:
mass = stats.binom.pmf(k,n,p)
wald = mass[abs(ph-p)<=wh].sum()
wilson = mass[abs(c-p)<=h+1e-12].sum()
print(p, "Wald",wald,"Wilson",wilson)There are only 21 possible observed counts, so summing their exact probabilities gives coverage without Monte Carlo error. Wilson is often better near the boundaries but still need not equal .95 at every \(p\).
12.7.6 Exercise 6: Bootstrap a robust summary (Python)
Generate 100 observations from a standard normal distribution, then replace the first three with the value eight to mimic contamination. Bootstrap both the mean and median, reporting their estimates, standard errors and percentile intervals. Interpret the difference.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1203)
x = rng.normal(size=100)
x[:3] = 8
idx = rng.integers(0,x.size,(4000,x.size))
b = x[idx]
for name, point, values in [
("mean",x.mean(),b.mean(axis=1)),
("median",np.median(x),np.median(b,axis=1))
]:
print(name,point,values.std(ddof=1),np.quantile(values,[.025,.975]))
plt.hist(values,bins=35,density=True,alpha=.5,label=name)
plt.legend()
plt.xlabel("Bootstrap statistic")
plt.show()The mean is affected by large observations, while the median resists their magnitudes as long as their fraction is small. Bootstrap resampling describes uncertainty relative to the contaminated sample; it does not recover an uncontaminated population by itself.