Module contents
Lesson 9 of 27Core 105 min

Confidence intervals

Construct and interpret confidence and prediction intervals, compare proportion intervals and profile likelihood, and measure coverage and tail behavior under realistic sampling.

After this lesson you can

  • Interpret confidence coverage and construct exact intervals using pivotal quantities.
  • Compare Wald, Wilson, Agresti–Coull and Clopper–Pearson intervals for a proportion.
  • Construct profile-likelihood intervals and understand reparameterization invariance.
  • Distinguish confidence intervals, prediction intervals and joint regions.
  • Assess coverage and tail errors by exact calculations and simulation.

Before you start

Motivation: a metric without an interval cannot decide

You evaluate two detectors on independent test sets of 200 labeled cases each. Detector A gets 168 right (84 %) and B gets 176 (88 %). Is B better? Point estimates alone cannot tell you, because you do not know how much each number would move if evaluation were repeated on another 200 cases. What is missing is a measure of that uncertainty, conventionally a confidence interval.

The next cell does two things. It calculates Wilson intervals (defined shortly) for A and B, and answers an uncomfortable question: if the two detectors were identical, with true accuracy 0.86, how often would a gap of at least 4 percentage points appear purely by chance between evaluations?

[ ]How much does accuracy measured on 200 cases move?Browser
import numpy as np
from scipy import stats

n, z = 200, 1.959964
for nombre, aciertos in [("A", 168), ("B", 176)]:
    p = aciertos / n
    centro = (p + z**2 / (2 * n)) / (1 + z**2 / n)
    mitad = z / (1 + z**2 / n) * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))
    print(f"detector {nombre}: exactitud {p:.3f}, intervalo de Wilson al 95 %: [{centro - mitad:.3f}, {centro + mitad:.3f}]")

# Si ambos detectores tuvieran exactitud 0.86, probabilidad exacta de ver una diferencia de >= 8 aciertos (4 puntos)
x = np.arange(n + 1)
pmf = stats.binom.pmf(x, n, 0.86)
dif = np.abs(x[:, None] - x[None, :])
print("P(|brecha| >= 4 puntos) con detectores idénticos:", round(float(np.sum(pmf[:, None] * pmf[None, :] * (dif >= 8))), 3))

More than once in four you would see such a gap without any real difference, and the two 95 % intervals overlap substantially. This lesson constructs those intervals rigorously and measures, in a simulation study, whether they deliver what they promise. It answers five questions:

  1. What exactly does “95 %” mean? It is a property of the procedure, not the particular resulting interval.
  2. How is an exact interval built? With pivotal quantities: the tt and χ2\chi^2 intervals of normal theory.
  3. What if there is no pivot? Wald intervals from the MLE, their failures, and the profile-likelihood alternative.
  4. Which interval for a proportion? Four candidates (Wald, Wilson, Agresti–Coull, Clopper–Pearson) with very different behavior.
  5. Interval for a parameter or the next observation? The distinction between confidence and prediction, which in machine learning separates model uncertainty from noise.

What “95 %” means: the frequentist definition

Work with a sample X=(X1,…,Xn)\vb{X} = (X_1, \dots, X_n) from a statistical model {Pθ:θ∈Θ}\{P_\theta : \theta \in \Theta\}, seeking a set of reasonable values for parameter θ∈R\theta \in \R. Neyman’s (1937) idea is to avoid assigning probability to θ\theta, an unknown constant, and instead require a guarantee about the procedure.

This is the confidence interval. Three details of the definition matter more than they seem.

  • The interval is random. In Pθ(L(X)≤θ≤U(X))\Pr_\theta(L(\vb{X}) \le \theta \le U(\vb{X})) probability is over samples the model could generate with fixed θ\theta. Once data are observed, [l,u][l, u] is a pair of numbers, and θ\theta either lies in it or does not: nothing remains over which to assign probability.
  • The guarantee is for every θ\theta. A procedure covering 99 % at some parameter values and 80 % at others is not at the 95 % level. The infimum matters, and as we will see for binomial proportions it can be disastrous even if average coverage is good.
  • Nominal is not actual. You choose level 1−α1 - \alpha; coverage C(θ)C(\theta) is what the procedure actually does. Exact intervals satisfy C(θ)=1−αC(\theta) = 1 - \alpha (or ≥\ge) at every finite sample size; approximate ones satisfy it only in the limit, and distance from that limit must be measured.

The first interactive makes the definition visible. Each row is a new sample, and its tt interval is plotted against the true mean.

InteractiveOne hundred intervals, one in twenty misses
95 % tt intervals for the mean, from 100 samples of size n=10n = 10 (normal)
μ
  • contains μ
  • misses μ
  • true mean
Population
10
95 %
100 intervals
Contain the mean (this batch)93 of 100
Actual long-run coverage94.8 % ± 0.3
Misses with interval above | below2.5 % | 2.7 %
Mean interval width1.39
Long-run coverage is 94.8 %, consistent with the nominal 95 % (Monte Carlo error ±0.3\pm 0.3 points).
Each bar is the tt interval for the mean of a sample of size nn; the point is its sample mean and the vertical line the true mean μ\mu. Intervals that miss it are red. With a normal distribution, any nn, and 95 %, in the long run 5 of 100 miss (in a particular batch it may be 2 or 9). With exponential or lognormal data and small nn, actual coverage is below nominal, and nearly all misses are on the same side: the interval lies below μ\mu. Long-run coverage is calculated from 20 000 samples with its Monte Carlo error.

Three lessons from the interactive. “95 %” is a long-run frequency: a batch of one hundred yields about five red intervals, not exactly five, and none “knows” it missed. The guarantee depends on assumptions: under normality the tt interval is exact for every n≥2n \ge 2 (coverage is always 95 % within simulation error); with exponential data and n=10n = 10 it covers around 90 %, and with lognormal (σ=1\sigma = 1) and n=10n = 10, around 84 %. Misses are not evenly distributed: with long right tails, the sample mean tends to fall below μ\mu, and the estimated standard deviation is small just when Xˉ\bar X is, so almost all misses are intervals entirely below μ\mu.

Correct and incorrect interpretations

Suppose you obtained [0.12,0.31][0.12, 0.31] as a 95 % interval for a proportion. Common readings include:

StatementCorrect?
“The procedure I used produces intervals containing pp in 95 % of repetitions of the experiment.”Yes: that is the definition.
“There is a 95 % probability that pp is in [0.12,0.31][0.12, 0.31].”No, in the frequentist framework: pp is not random and the interval is fixed. (With a prior distribution for pp a statement like this exists, but it is a Bayesian credible interval, a different object: lesson 21.)
“95 % of observations fall in [0.12,0.31][0.12, 0.31].”No: that would be a tolerance or prediction interval, and much wider.
“If I repeat the study, the new estimate will fall in [0.12,0.31][0.12, 0.31] with probability 95 %.”No. For a normal mean, the probability that a replicate mean falls in the first interval is 2Φ(1.96/2)−1≈83.42\Phi(1.96/\sqrt 2) - 1 \approx 83.4 %.

The last figure follows because the difference of two independent means has twice the variance. This is a widespread error, corrected by remembering that the interval quantifies uncertainty about the parameter, not future estimates.

Pivotal quantities

How do we build an interval with exact coverage? The classical tool is a function of data and parameter whose distribution depends on nothing unknown.

A pivotal quantity differs from a statistic because it depends on the parameter, but differs from an arbitrary variable because its law is known. The recipe is mechanical. Choose a,ba, b with P(a≤Q≤b)=1−α\Pr(a \le Q \le b) = 1 - \alpha under GG (e.g. its α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles) and solve a≤Q(X,θ)≤ba \le Q(\vb{X}, \theta) \le b for θ\theta. Since the inequality’s probability does not depend on θ\theta, neither does that of the resulting interval: coverage is exactly 1−α1 - \alpha for every θ\theta.

Normal mean. With Xi∼iidN(μ,σ2)X_i \iid \Normal(\mu, \sigma^2), by normal sampling theory Xˉ⊥ ⁣ ⁣ ⁣⊥S2\bar X \indep S^2, Xˉ∼N(μ,σ2/n)\bar X \sim \Normal(\mu, \sigma^2/n) and (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1}. If σ\sigma is known, n(Xˉ−μ)/σ∼N(0,1)\sqrt n(\bar X - \mu)/\sigma \sim \Normal(0, 1) is a pivot. Otherwise, the ratio of a standard normal to the square root of an independent χn−12\chi^2_{n-1} divided by its degrees of freedom is Student’s tt:

T=n (Xˉ−μ)S∼tn−1⟹Xˉ±tn−1, 1−α/2 Sn.T = \frac{\sqrt n\,(\bar X - \mu)}{S} \sim t_{n-1} \quad\Longrightarrow\quad \bar X \pm t_{n-1,\,1-\alpha/2}\,\frac{S}{\sqrt n}.

The unknown variance has been absorbed into the pivot’s distribution: that is what it does. The tt has heavier tails than the normal; with n=10n = 10, t9, 0.975=2.262t_{9,\,0.975} = 2.262 versus 1.9601.960, and the correction vanishes as nn grows.

Normal variance. The pivot (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1} gives

P(χn−1, α/22≤(n−1)S2σ2≤χn−1, 1−α/22)=1−α⟹[(n−1)S2χn−1, 1−α/22, (n−1)S2χn−1, α/22].\Pr\Big(\chi^2_{n-1,\,\alpha/2} \le \frac{(n - 1)S^2}{\sigma^2} \le \chi^2_{n-1,\,1-\alpha/2}\Big) = 1 - \alpha \quad\Longrightarrow\quad \Big[\frac{(n - 1)S^2}{\chi^2_{n-1,\,1-\alpha/2}},\ \frac{(n - 1)S^2}{\chi^2_{n-1,\,\alpha/2}}\Big].

It is not symmetric around S2S^2: the upper end is farther away because χ2\chi^2 is skewed.

Exponential rate. With Xi∼iidExp(λ)X_i \iid \mathrm{Exp}(\lambda), ∑iXi∼Gamma(n,λ)\sum_i X_i \sim \mathrm{Gamma}(n, \lambda), so 2λ∑iXi∼χ2n22\lambda \sum_i X_i \sim \chi^2_{2n} is a pivot. The interval is λ^ [χ2n, α/22, χ2n, 1−α/22]/(2n)\hat\lambda\,[\chi^2_{2n,\,\alpha/2},\ \chi^2_{2n,\,1-\alpha/2}]/(2n) with λ^=n/∑Xi\hat\lambda = n/\sum X_i. We will use it as an exact reference. In general, for any continuous family, −2∑ilog⁡Fθ(Xi)∼χ2n2-2\sum_i \log F_\theta(X_i) \sim \chi^2_{2n} by the probability integral transform: a pivot always exists, although solving for θ\theta may not be possible in closed form.

Duality with tests

One idea underlies every interval in this lesson. An interval is the set of parameter values that would not be rejected as the null hypothesis. Tests are studied in lesson 10; here only the notion of an acceptance region is needed.

Proof

For every θ\theta, θ∈C(X)  ⟺  X∈A(θ)\theta \in \mathcal{C}(\vb{X}) \iff \vb{X} \in A(\theta) by definition of C\mathcal{C}, so Pθ(θ∈C(X))=Pθ(X∈A(θ))≥1−α\Pr_\theta(\theta \in \mathcal{C}(\vb{X})) = \Pr_\theta(\vb{X} \in A(\theta)) \ge 1 - \alpha. The converse is the same equivalence read backward.

∎

This duality turns any test whose level is known into an interval. Wilson inverts the score test, Clopper–Pearson inverts exact binomial tests, and likelihood intervals invert likelihood-ratio tests. Interval quality inherits test quality: its coverage is test level at each point, width reflects power (a more powerful test rejects more false values and leaves a shorter interval), and shape follows the acceptance region.

The χ2\chi^2 pivot is fragile

An interval exact under normality says nothing about what happens outside that assumption. The tt and χ2\chi^2 pivots behave very differently.

The tt interval is asymptotically robust: by the central limit theorem and Slutsky’s lemma, n(Xˉ−μ)/S→N(0,1)\sqrt n(\bar X - \mu)/S \to \Normal(0, 1) for any population with finite variance. But convergence is slow under skewness. The Edgeworth expansion of the studentized statistic gives, for a population with skewness coefficient γ\gamma,

P(T≤−z)≈α2+γ6n (2z2+1) φ(z),\Pr(T \le -z) \approx \frac{\alpha}{2} + \frac{\gamma}{6\sqrt n}\,(2z^2 + 1)\,\varphi(z),

and the opposite tail deviates in the opposite direction: first-order errors cancel in total coverage (error of order 1/n1/n), but not in each tail (error of order 1/n1/\sqrt n). The interactive shows this.

The χ2\chi^2 variance interval is much worse, for a transparent reason. With κ=E[(X−μ)4]/σ4\kappa = \E[(X - \mu)^4]/\sigma^4 the kurtosis (3 for normal), Var⁡(S2)≈σ4(κ−1)/n\Var(S^2) \approx \sigma^4(\kappa - 1)/n, while the χn−12\chi^2_{n-1} law assumes 2σ4/(n−1)2\sigma^4/(n - 1), equivalent to κ=3\kappa = 3. By the CLT, n(S2/σ2−1)→N(0,κ−1)\sqrt n(S^2/\sigma^2 - 1) \to \Normal(0, \kappa - 1) in distribution, and the interval, which for large nn behaves like S2/σ2∈1±z2/nS^2/\sigma^2 \in 1 \pm z\sqrt{2/n}, has asymptotic coverage

P(∣Z∣≤z1−α/22κ−1),Z∼N(0,1).\Pr\Big(\abs{Z} \le z_{1-\alpha/2}\sqrt{\tfrac{2}{\kappa - 1}}\Big), \qquad Z \sim \Normal(0, 1).

With κ=3\kappa = 3 this is 95 %. With exponential data (κ=9\kappa = 9) it is P(∣Z∣≤0.98)≈67\Pr(\abs{Z} \le 0.98) \approx 67 %, and does not improve as nn grows (it is the limit): this is not a small-sample issue, but a pivot depending on an assumption (kurtosis) the data do not satisfy.

[ ]The t pivot holds up, the χ² pivot does notBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
z = stats.norm.ppf(0.975)

def coberturas(muestreo, mu, var, n, R=20000):
    x = muestreo((R, n))
    m, s2 = x.mean(axis=1), x.var(axis=1, ddof=1)
    mitad = stats.t.ppf(0.975, n - 1) * np.sqrt(s2 / n)
    lo = (n - 1) * s2 / stats.chi2.ppf(0.975, n - 1)
    hi = (n - 1) * s2 / stats.chi2.ppf(0.025, n - 1)
    return (np.mean(np.abs(m - mu) <= mitad),            # intervalo t
            np.mean((lo <= var) & (var <= hi)),          # intervalo chi2 para la varianza
            np.mean(m + mitad < mu))                     # t: intervalo entero por debajo de mu

print("población      n   cobertura t   cobertura chi2   t falla por debajo")
for nombre, f, mu, var in [("normal", lambda s: rng.normal(size=s), 0.0, 1.0),
                           ("exponencial", lambda s: rng.exponential(size=s), 1.0, 1.0)]:
    for n in [20, 100, 400]:
        ct, cv, abajo = coberturas(f, mu, var, n)
        print(f"{nombre:12s} {n:4d}      {ct:.3f}         {cv:.3f}           {abajo:.3f}")

# primer orden de Edgeworth para la cola inferior del estadístico t (exponencial: asimetría 2)
for n in [20, 100, 400]:
    ed = 0.025 + 2 / (6 * np.sqrt(n)) * (2 * z**2 + 1) * stats.norm.pdf(z)
    print(f"n = {n}: cola inferior según Edgeworth {ed:.3f}")
print("cobertura asintótica del intervalo chi2 con curtosis 9:", round(2 * stats.norm.cdf(z * np.sqrt(2 / 8)) - 1, 3))

For exponential data, tt coverage rises toward 0.95 as nn increases with misses concentrated in one tail, and the Edgeworth prediction gets the order of magnitude right; χ2\chi^2 coverage falls toward 0.67 and does not improve. Practical lesson: normality-based intervals for variances are not used with real data; for variances and standard deviations prefer intervals not depending on kurtosis, such as bootstrap intervals in lessons 16 and 17.

Wald intervals

There is almost never an exact pivot. But asymptotic normality of the MLE provides an approximate pivot: (θ^−θ)/SE^≈N(0,1)(\hat\theta - \theta)/\widehat{\mathrm{SE}} \approx \Normal(0, 1), where SE^\widehat{\mathrm{SE}} is an estimated standard error, e.g. (n I(θ^))−1/2(n\,I(\hat\theta))^{-1/2} or J(θ^)−1/2J(\hat\theta)^{-1/2}, with JJ the observed information.

Proof

(θ^n−θ)/SE^n=n(θ^n−θ)/σ^n(\hat\theta_n - \theta)/\widehat{\mathrm{SE}}_n = \sqrt n(\hat\theta_n - \theta)/\hat\sigma_n converges in distribution by Slutsky to N(0,σ2)/σ=N(0,1)\Normal(0, \sigma^2)/\sigma = \Normal(0, 1). The interval covers θ\theta if and only if the ratio is in [−z,z][-z, z], and since the limiting law is continuous, probability converges to P(∣Z∣≤z)=1−α\Pr(\abs{Z} \le z) = 1 - \alpha.

∎

This defines the Wald interval: estimator plus or minus zz standard errors. For a function g(θ)g(\theta) use the delta method: g(θ^)±z ∣g′(θ^)∣SE^g(\hat\theta) \pm z\,\abs{g'(\hat\theta)}\widehat{\mathrm{SE}}. It is convenient (one fit and a subtraction), and what almost all software prints. But the theorem hides three traps:

  1. “For each fixed θ\theta” is not “uniformly”. Sample size needed to approach 95 % can grow without bound as θ\theta approaches the boundary. For a proportion, the infimum over pp of Wald coverage is near 0 for any nn.
  2. It depends on parameterization. A Wald interval for θ\theta and one for ϕ=log⁡θ\phi = \log\theta transformed back with exp⁡\exp are different intervals for the same parameter, both asymptotically correct but very different at finite nn. If the MLE distribution is highly skewed on one scale, the normal approximation is bad on that scale and good on another.
  3. It uses SE^\widehat{\mathrm{SE}} at θ^\hat\theta, not at the value being tested. When variance depends on the parameter, random θ^\hat\theta can systematically fail: with p^=0\hat p = 0 estimated standard error is 0 and the interval is a point.

The last point motivates inverting a test instead of solving with estimated standard error: evaluate variance at hypothetical θ0\theta_0, not at θ^\hat\theta. This is what Wilson (score) and likelihood do.

A proportion: four intervals

The most frequent model-evaluation case is X∼Bin⁡(n,p)X \sim \Bin(n, p) with XX the number correct, and p^=X/n\hat p = X/n. It is also instructive because it has exact solutions for comparison and an anomaly affecting all approximate intervals: XX is discrete, causing coverage to oscillate.

These are binomial proportion intervals. Each has a distinct interpretation worth understanding.

Wald is the naive interval: standardize p^\hat p with estimated standard error. Wilson inverts the score test (lesson 11): in testing H0:p=p0H_0: p = p_0, variance is evaluated at p0p_0, not p^\hat p, so the interval always lies in [0,1][0, 1] and never degenerates: with x=0x = 0 it is [0, z2/(n+z2)][0,\ z^2/(n + z^2)]. Its center, (x+z2/2)/(n+z2)(x + z^2/2)/(n + z^2), is a weighted average of p^\hat p (weight nn) and 1/21/2 (weight z2z^2): shrinkage toward 1/21/2 that grows as nn shrinks. Agresti–Coull uses the same center with Wald’s formula and is therefore always slightly wider than Wilson. You will derive Wilson in the first proof exercise.

Clopper–Pearson inverts two exact binomial tail tests. To understand it, use the binomial–beta relationship: Pp(X≥x)=Ip(x, n−x+1)\Pr_p(X \ge x) = I_p(x,\ n - x + 1), the distribution function in pp of a Beta(x,n−x+1)\mathrm{Beta}(x, n - x + 1). Since p↦Pp(X≥x)p \mapsto \Pr_p(X \ge x) increases, the lower endpoint is the pp where Pp(X≥x)=α/2\Pr_p(X \ge x) = \alpha/2, and the upper where Pp(X≤x)=α/2\Pr_p(X \le x) = \alpha/2.

Proof

Let Gp(x)=Pp(X≥x)G_p(x) = \Pr_p(X \ge x), nonincreasing in xx and increasing in pp. By construction, L(x)L(x) is the unique pp with Gp(x)=α/2G_p(x) = \alpha/2, so L(x)>pL(x) > p is equivalent to Gp(x)<α/2G_p(x) \lt \alpha/2. Since GpG_p is nonincreasing in xx, the set {x:Gp(x)<α/2}\{x : G_p(x) \lt \alpha/2\} has form {x≥x∗}\{x \ge x^*\}, with x∗x^* its least element, and probability Pp(X≥x∗)=Gp(x∗)<α/2\Pr_p(X \ge x^*) = G_p(x^*) \lt \alpha/2. Thus Pp(L(X)>p)≤α/2\Pr_p(L(X) > p) \le \alpha/2. The same argument with Pp(X≤x)\Pr_p(X \le x) gives Pp(U(X)<p)≤α/2\Pr_p(U(X) \lt p) \le \alpha/2, and the union bound gives Pp(p∉[L,U])≤α\Pr_p(p \notin [L, U]) \le \alpha.

∎

The exact guarantee has a cost: the inequality is almost always strict (because XX is discrete, exact α/2\alpha/2 cannot be attained), so the interval is conservative: it covers more than its promised 95 %.

Sawtooth coverage

How much do they really cover? For x=0,…,nx = 0, \dots, n each method gives an interval [L(x),U(x)][L(x), U(x)], and coverage at pp is exactly

C(p)=∑x=0nBin⁡(x; n,p) 1[ L(x)≤p≤U(x) ],C(p) = \sum_{x = 0}^n \Bin(x;\, n, p)\ \ind\big[\,L(x) \le p \le U(x)\,\big],

without simulation: a finite sum. Plotted as a function of pp it is not smooth. When pp crosses an endpoint L(x)L(x) or U(x)U(x), xx enters or leaves the set of covering outcomes, and C(p)C(p) jumps by the binomial mass of xx, of order 1/np(1−p)1/\sqrt{np(1-p)}. This produces sawtooth oscillations of amplitude O(1/n)\bigO(1/\sqrt n) that do not disappear quickly. Brown, Cai and DasGupta (2001) study them in depth.

InteractiveSawtooth coverage
Exact 95% coverage versus pp, with n=50n = 50 (values show coverage at marked pp, minimum and mean over the range)
The four intervals for x=3x = 3 of n=50n = 50 (p^=0.060\hat p = 0.060); dimmed if they do not contain the marked pp
Wald [0.000, 0.126] · Wilson [0.021, 0.162] · Agresti-Coull [0.014, 0.168] · Clopper-Pearson [0.013, 0.165]
  • nominal level 95%
  • marked value of p
  • estimate p^=x/n\hat p = x/n
50
Range of pp
Vertical scale
0.030
3 of 50
Waldat p: 78.1 % · min 2.5 % · mean 90.1 %
Wilsonat p: 93.7 % · min 84.7 % · mean 95.2 %
Agresti-Coullat p: 98.3 % · min 93.5 % · mean 95.8 %
Clopper-Pearsonat p: 98.3 % · min 95.1 % · mean 96.9 %
Wald coverage falls to 2.5 % for some pp in the range and below 93% for 40 % of pp values. Clopper-Pearson stays at or above 95.1 %.
Above: exact 95 % coverage of each interval as a function of true proportion pp, for your chosen nn. Below: all four intervals for your chosen success count xx; those not containing marked pp (dotted line) are faded. With n=50n = 50 and range [0,0.1][0, 0.1]: Wald collapses near 0, Wilson oscillates around 95 % with some dips below 90 % very near p=0p = 0, Agresti–Coull (enable it) barely drops below 93 %, and Clopper–Pearson never drops below 95 %, at the cost of remaining around 97 %. Increase nn to 1000: Wald's collapse does not disappear, only moves toward p=0p = 0.

Four observations, all checkable by moving the interactive.

Wald fails where it matters. With n=50n = 50 average coverage is 90 %, below 93 % for four in ten values of pp in [0,0.5][0, 0.5]. Near 0 it is worse: for p=λ/np = \lambda/n with small λ\lambda, XX is nearly Poisson, P(X=0)≈e−λ\Pr(X = 0) \approx e^{-\lambda}, and with X=0X = 0 the interval is point {0}\{0\}, which does not contain p>0p > 0. Thus coverage is bounded by 1−(1−λ/n)n1 - (1 - \lambda/n)^n, tending to 1−e−λ1 - e^{-\lambda} and barely changing with nn: the ceiling is the same for any large nn. For p=0.5/np = 0.5/n and n≥10n \ge 10 it is at most 40 %. Increasing nn only moves the collapse toward smaller pp.

Wilson oscillates around 95 % (average 95 %, with occasional dips below 90 % at very small pp). Agresti–Coull is slightly more conservative than Wilson and rarely drops below 93 %. Clopper–Pearson guarantees 95 % in the worst case, but averages 97 % coverage at n=50n = 50: the excess is wasted information, unnecessarily wide intervals.

Brown, Cai and DasGupta recommend Wilson (or Jeffreys’ interval, the Bayesian interval from lesson 21 with prior Beta(1/2,1/2)\mathrm{Beta}(1/2, 1/2)) for small nn and Agresti–Coull for larger nn, and advise against Wald even at large nn. Clopper–Pearson is the option when minimum coverage is required (e.g. a validation report), knowing it overcovers.

Lab: coverage from scratch

We implement five procedures (the four plus likelihood ratio, covered shortly), measure exact coverage, and reproduce the Brown–Cai–DasGupta figure. Everything is vectorized: coverage at pp is a weighted sum of masks.

[ ]Coverage lab: five intervals and their exact coverageBrowser
import numpy as np
from scipy import stats, optimize, special
import matplotlib.pyplot as plt

Z = stats.norm.ppf(0.975)

def ic_wald(x, n, z=Z):
    p = x / n
    h = z * np.sqrt(p * (1 - p) / n)
    return np.clip(p - h, 0, 1), np.clip(p + h, 0, 1)

def ic_wilson(x, n, z=Z):
    p = x / n
    centro = (p + z**2 / (2 * n)) / (1 + z**2 / n)
    h = z / (1 + z**2 / n) * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))
    return np.clip(centro - h, 0, 1), np.clip(centro + h, 0, 1)

def ic_agresti_coull(x, n, z=Z):
    nt = n + z**2
    pt = (x + z**2 / 2) / nt
    h = z * np.sqrt(pt * (1 - pt) / nt)
    return np.clip(pt - h, 0, 1), np.clip(pt + h, 0, 1)

def ic_clopper_pearson(x, n, alfa=0.05):
    lo = np.where(x == 0, 0.0, stats.beta.ppf(alfa / 2, np.maximum(x, 1), n - x + 1))
    hi = np.where(x == n, 1.0, stats.beta.ppf(1 - alfa / 2, x + 1, np.maximum(n - x, 1)))
    return lo, hi

def ic_verosimilitud(x, n, nivel=0.95):
    """Razón de verosimilitudes: {p : 2[l(p_hat) - l(p)] <= chi2_1(nivel)}, con raíces por brentq."""
    corte = stats.chi2.ppf(nivel, 1) / 2
    lo, hi = np.zeros(len(x)), np.ones(len(x))
    for i, xi in enumerate(x):
        ll = lambda p: special.xlogy(xi, p) + special.xlog1py(n - xi, -p)   # 0 log 0 = 0
        ph = xi / n
        f = lambda p: ll(p) - ll(ph) + corte
        if xi > 0:
            lo[i] = optimize.brentq(f, 1e-12, ph)
        if xi < n:
            hi[i] = optimize.brentq(f, ph, 1 - 1e-12)
    return lo, hi

def cobertura(metodo, n, ps):
    """C(p) = sum_x Bin(x; n, p) * 1[p en IC(x)], exacta."""
    x = np.arange(n + 1)
    lo, hi = metodo(x, n)
    pmf = stats.binom.pmf(x[None, :], n, ps[:, None])
    cubre = (lo[None, :] <= ps[:, None]) & (ps[:, None] <= hi[None, :])
    return np.sum(pmf * cubre, axis=1)

METODOS = {"Wald": ic_wald, "Wilson": ic_wilson, "Agresti-Coull": ic_agresti_coull,
           "Clopper-Pearson": ic_clopper_pearson, "Verosimilitud": ic_verosimilitud}

n = 50
ps = np.linspace(0.001, 0.5, 2000)
curvas = {nombre: cobertura(f, n, ps) for nombre, f in METODOS.items()}
print(f"n = {n}, p en [0.001, 0.5]")
print("método              mínima   media   p con cobertura < 93 %")
for nombre, c in curvas.items():
    print(f"{nombre:16s}   {c.min():.3f}   {c.mean():.3f}   {np.mean(c < 0.93):6.1%}")

fig, ax = plt.subplots(figsize=(8, 3.6))
for nombre in ["Wald", "Wilson", "Clopper-Pearson"]:
    ax.plot(ps, curvas[nombre], lw=1.2, label=nombre)
ax.axhline(0.95, color="gray", ls="--")
ax.set_ylim(0.6, 1.0); ax.set_xlabel("p"); ax.set_ylabel("cobertura"); ax.legend(loc="lower right")
plt.show()

The table is the figure in numbers. Wald has a minimum near 0.05 (at p=0.001p = 0.001, where a success is rarely observed) and falls below 93 % over 40 % of the range; Wilson has a minimum near 0.84 and almost always covers well; Agresti–Coull does not fall below 0.93 and Clopper–Pearson not below 0.95, with average 97 %. The likelihood interval, built next, has minimum (0.84) and average (0.95) similar to Wilson, as expected from two approximations to the same test, although it falls below 93 % for more pp values (8 % versus 1.4 %).

Profile likelihood

Wald requires θ^\hat\theta to be approximately normal on its parameterization scale. Log-likelihood gives an alternative without that requirement. Near the maximum a second-order Taylor expansion gives

ℓ(θ)−ℓ(θ^)≈−12 (θ^−θ)2SE^2,\ell(\theta) - \ell(\hat\theta) \approx -\frac{1}{2}\,\frac{(\hat\theta - \theta)^2}{\widehat{\mathrm{SE}}^2},

a parabola, and the Wald interval is exactly where that parabola lies above −z2/2-z^2/2. But the true log-likelihood is not a parabola. The idea is to cut the true curve at that height, not its approximation. With multiple parameters, decide what to do with those not of interest (nuisance parameters): maximize over them for each value of the parameter of interest, yielding a function of one parameter.

This is the profile likelihood interval. Its justification is Wilks’ theorem (lesson 11): under MLE conditions, 2[ℓp(ψ^)−ℓp(ψ0)]→χ122[\ell_p(\hat\psi) - \ell_p(\psi_0)] \to \chi^2_1 in distribution. When the parabola is exact, this statistic is the squared Wald pivot and the two intervals coincide; otherwise the likelihood interval follows the curve’s real shape. For 95 % the line is at −χ1, 0.952/2=−1.921-\chi^2_{1,\,0.95}/2 = -1.921 (because χ1, 0.952=3.841=1.962\chi^2_{1,\,0.95} = 3.841 = 1.96^2).

It has a property Wald does not.

This follows because ℓp(ϕ)=ℓp(h−1(ϕ))\ell_p(\phi) = \ell_p(h^{-1}(\phi)) (likelihood at a point does not depend on its name) and the MLE is equivariant: ϕ^=h(ψ^)\hat\phi = h(\hat\psi). The last exercise gives the full proof. A Wald interval, by contrast, is not invariant: it depends on the scale used for the normal approximation.

The interactive shows this for exponential rate λ\lambda. With nn observations and t=λ/λ^t = \lambda/\hat\lambda, relative log-likelihood is n(log⁡t−t+1)n(\log t - t + 1), which does not depend on data except via λ^\hat\lambda. Its curve has a long right tail in λ\lambda (hence is skewed) and is much more symmetric in log⁡λ\log\lambda.

InteractiveCutting the likelihood
Relative log-likelihood ℓ(λ)−ℓ(λ^)\ell(\lambda) - \ell(\hat\lambda) of an exponential rate with n=5n = 5 observations, with axis λ/λ^\lambda/\hat\lambda
−1.92
The four 95.0 % intervals on the same axis. Dimmed: the Wald interval in the other parameterization.
  • likelihood (cutoff)
  • Wald in λ\lambda
  • Wald in log⁡λ\log\lambda
  • exact (reference)
5
95.0 %
Horizontal axis and Wald parabola
Likelihood (endpoints in units of λ^\hat\lambda)[0.359, 2.149] · coverage 94.6 % (misses: λ above 1.8 % | λ below 3.6 %)
Wald in λ\lambda[0.123, 1.877] · coverage 95.6 % (misses: λ above 4.3 % | λ below 0.0 %)
Wald in log⁡λ\log\lambda[0.416, 2.403] · coverage 93.2 % (misses: λ above 0.8 % | λ below 6.0 %)
Exact (χ2n2\chi^2_{2n} pivot)[0.325, 2.048] · coverage 95.0 % (misses: λ above 2.5 % | λ below 2.5 %)
The likelihood interval covers 94.6 % (nominal 95.0 %) and the Wald interval in λ\lambda covers 95.6 %, but almost all its misses are on the same side.
The magenta curve is relative log-likelihood for an exponential rate; the horizontal line is at −χ12(nivel)/2-\chi^2_1(\text{nivel})/2 and its handle (circle) can be dragged. Magenta intersections are likelihood-interval endpoints. The dashed parabola is Wald's approximation in the chosen parameterization. Switch the axis to log⁡λ\log\lambda: the curve deforms and parabola changes, but likelihood endpoints measured in λ\lambda do not move. Exact coverage is computed (via λ/λ^∼Gamma(n,1/n)\lambda/\hat\lambda \sim \mathrm{Gamma}(n, 1/n)), together with the split of misses between tails.

With n=10n = 10 and 95 %, as multiples of λ^\hat\lambda: the exact interval (χ2n2\chi^2_{2n} pivot) is [0.480,1.708][0.480, 1.708]; likelihood [0.501,1.754][0.501, 1.754]; Wald on λ\lambda [0.380,1.620][0.380, 1.620]; and Wald on log⁡λ\log\lambda [0.538,1.859][0.538, 1.859]. Exact coverages are 95.0 %, 94.8 %, 95.5 %, and 94.1 %. Looking only at total coverage would make Wald on λ\lambda seem best, incorrectly: its lower endpoint is far too low and upper endpoint too short, so it misses 3.9 % on one side and 0.6 % on the other. Wald on log⁡λ\log\lambda misses in reverse (1.1 % and 4.8 %), the exact interval splits misses evenly (2.5 % and 2.5 %), and likelihood is close (2.0 % and 3.2 %). Differences are larger at n=5n = 5. Total coverage is not enough: examine both tails.

The likelihood interval is not exact (94.8 % at n=10n = 10): its coverage error is of order 1/n1/n, and Bartlett correction reduces it to 1/n21/n^2. But it follows the true shape more closely and is invariant, making it reliable when the scale on which normality works well is unknown.

[ ]Invariance: likelihood intervals in λ and log λBrowser
import numpy as np
from scipy import stats, optimize

n = 10
corte = stats.chi2.ppf(0.95, 1) / 2
# log-verosimilitud relativa de la tasa exponencial en la escala t = lambda / lambda_hat
rel_ll = lambda t: n * (np.log(t) - t + 1)

def extremos(f, centro, limites):
    """Raíces de f(u) = -corte a cada lado del máximo."""
    g = lambda u: f(u) + corte
    return optimize.brentq(g, limites[0], centro), optimize.brentq(g, centro, limites[1])

lo, hi = extremos(rel_ll, 1.0, (1e-6, 50.0))                          # en la escala de lambda
lo2, hi2 = extremos(lambda u: rel_ll(np.exp(u)), 0.0, (-20.0, 20.0))  # en la escala de log lambda
print(f"verosimilitud en lambda:      [{lo:.6f}, {hi:.6f}]")
print(f"verosimilitud en log lambda:  [{np.exp(lo2):.6f}, {np.exp(hi2):.6f}]  (tras exponenciar)")

z = stats.norm.ppf(0.975)
print(f"Wald en lambda:      [{1 - z / np.sqrt(n):.3f}, {1 + z / np.sqrt(n):.3f}]")
print(f"Wald en log lambda:  [{np.exp(-z / np.sqrt(n)):.3f}, {np.exp(z / np.sqrt(n)):.3f}]")
ex = stats.chi2.ppf([0.025, 0.975], 2 * n) / (2 * n)
print(f"exacto (chi2_2n):    [{ex[0]:.3f}, {ex[1]:.3f}]")

# cobertura exacta: lambda / lambda_hat ~ Gamma(n, escala 1/n)
G = stats.gamma(n, scale=1 / n)
for nombre, (a, b) in {"verosimilitud": (lo, hi), "Wald en lambda": (1 - z / np.sqrt(n), 1 + z / np.sqrt(n)),
                       "Wald en log lambda": (np.exp(-z / np.sqrt(n)), np.exp(z / np.sqrt(n)))}.items():
    print(f"{nombre:19s} cobertura {G.cdf(b) - G.cdf(a):.3f}   fallos: por encima {1 - G.cdf(b):.3f}, por debajo {G.cdf(a):.3f}")

The first two lines agree to the sixth digit: this is the theorem, not numerical coincidence. The others show what the interactive predicts.

Prediction intervals

Until now the target was a parameter. In machine learning another question often matters: where will the next observation fall? This is a different question with a different interval.

This is the prediction interval. There are two sources of uncertainty and a confidence interval captures only one: μ\mu is unknown (uncertainty shrinks with nn), and Xn+1X_{n+1} has its own noise, σ2\sigma^2, which no sample size reduces.

Normal case. Xn+1−XˉX_{n+1} - \bar X is normal with mean 0 and variance σ2(1+1/n)\sigma^2(1 + 1/n), independent of SS; the pivot (Xn+1−Xˉ)/(S1+1/n)∼tn−1(X_{n+1} - \bar X)/(S\sqrt{1 + 1/n}) \sim t_{n-1} gives

Xˉ±tn−1, 1−α/2 S1+1n.\bar X \pm t_{n-1,\,1-\alpha/2}\,S\sqrt{1 + \frac1n}.

Compared with confidence interval Xˉ±t S/n\bar X \pm t\,S/\sqrt n, the difference is “1 +” under the root. As n→∞n \to \infty the confidence interval shrinks like 1/n1/\sqrt n and the prediction interval tends to Xˉ±zσ\bar X \pm z\sigma, with fixed width 2zσ2z\sigma.

Without assuming a distribution. One construction uses only exchangeability.

Proof

Let RR be the rank of Xn+1X_{n+1} among the n+1n + 1 observations. Since they are iid with a continuous distribution (no ties with probability 1), all orderings are equally likely and RR is uniform on {1,…,n+1}\{1, \dots, n + 1\}. Thus Xn+1≥X(j)X_{n+1} \ge X_{(j)} is equivalent to R≥j+1R \ge j + 1, and Xn+1≤X(k)X_{n+1} \le X_{(k)} to R≤kR \le k. The event is R∈{j+1,…,k}R \in \{j + 1, \dots, k\}, with k−jk - j values, probability (k−j)/(n+1)(k - j)/(n + 1).

∎

Coverage is distribution-free (continuity suffices). The interval [X(j),X(n+1−j)][X_{(j)}, X_{(n+1-j)}] covers exactly (n+1−2j)/(n+1)(n + 1 - 2j)/(n + 1). For 95 % take j=⌊(n+1)α/2⌋j = \lfloor(n + 1)\alpha/2\rfloor (the largest jj not exceeding the target), requiring n≥39n \ge 39: with j=1j = 1, 1−2/(n+1)≥0.951 - 2/(n+1) \ge 0.95 is equivalent to n≥39n \ge 39. With less data even [X(1),X(n)][X_{(1)}, X_{(n)}] cannot reach 95 %. With n=19n = 19, for example, the sample range covers only 18/20=9018/20 = 90 %.

This is the germ of conformal prediction in m30: replace “rank of the new observation among the n+1n + 1” with “rank of an error score” to obtain the same distribution-free guarantee for any model.

InteractiveConfidence versus prediction
A sample of n=20n = 20 and its three 95% intervals
CI [−0.43, 0.22] · normal prediction [−1.61, 1.40] · order [−1.41, 1.20]
Typical width (in standard deviations σ\sigma) versus nn
central 95% of population: 3.92
  • CI for the mean
  • normal prediction
  • order prediction
  • true mean
Population
20
Width in standard deviations: mean CI | normal prediction | order prediction0.94 | 4.29 | 3.34
Normal prediction: covers next observation95.5 % (above 2.1 % | below 2.4 %)
Order prediction: exact | simulated coverage90.48 % | 91.1 %
Using the mean CI for predictioncovers only 33.3 %
With n=20n = 20, there is no 95% prediction interval based on order statistics: even [X(1),X(n)][X_{(1)}, X_{(n)}] falls short (its coverage is (n−1)/(n+1)(n - 1)/(n + 1), or 90.5 %). You need n≥39n \ge 39.
Left: a sample of size nn with population density, confidence interval for the mean (blue), normal prediction interval (orange), and order-statistic prediction interval (magenta). Right: typical width of each in standard deviations versus nn (log scale), calculated with s=σs = \sigma and, for order statistics, theoretical population quantiles. Increase nn: blue tends to 0 and the other two to fixed width. With exponential or lognormal data, normal prediction is too short above and wastes width below; order statistics split misses evenly and retain exact coverage. If you used the confidence interval to predict, at large nn it would cover almost no observations.

Three readings. Uncertainty that does not shrink. At n=2000n = 2000, the confidence interval is 0.09 σ0.09\,\sigma wide and prediction intervals 3.9 σ3.9\,\sigma (for normal), about 45 times wider. Confidence intervals say how much you know about the model; prediction intervals, how much about data. In machine learning this is the distinction between epistemic uncertainty (reducible with data) and aleatoric uncertainty (intrinsic noise). Total coverage hides the split. For exponential data with n=100n = 100, normal prediction covers 94.7 %, seemingly reasonable, but its lower endpoint is negative (for a positive quantity) and almost all misses are above. The order interval assumes no distribution: exact 96.0 % at n=100n = 100 (j=2j = 2) under any continuous law. This is coverage averaged over samples; conditional on a particular sample, coverage of [X(j),X(k)][X_{(j)}, X_{(k)}] is random with law Beta(k−j, n−k+j+1)\mathrm{Beta}(k - j,\ n - k + j + 1) and mean (k−j)/(n+1)(k - j)/(n + 1).

[ ]Order-statistic versus normal predictionBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(5)
n, R = 100, 40000
j = int(np.floor((n + 1) * 0.05 / 2))
print(f"n = {n}: j = {j}, cobertura teórica del intervalo de orden (n+1-2j)/(n+1) = {(n + 1 - 2 * j) / (n + 1):.4f}\n")

for nombre, f in [("normal", lambda s: rng.normal(size=s)),
                  ("exponencial", lambda s: rng.exponential(size=s)),
                  ("lognormal", lambda s: np.exp(rng.normal(size=s)))]:
    x, nuevo = f((R, n)), f(R)
    xs = np.sort(x, axis=1)
    orden_lo, orden_hi = xs[:, j - 1], xs[:, n - j]
    m, s = x.mean(axis=1), x.std(axis=1, ddof=1)
    h = stats.t.ppf(0.975, n - 1) * s * np.sqrt(1 + 1 / n)
    print(f"{nombre:12s} orden: cubre {np.mean((orden_lo <= nuevo) & (nuevo <= orden_hi)):.3f} "
          f"(por debajo {np.mean(nuevo < orden_lo):.3f}, por encima {np.mean(nuevo > orden_hi):.3f})   "
          f"normal: cubre {np.mean(np.abs(nuevo - m) <= h):.3f} "
          f"(por debajo {np.mean(nuevo < m - h):.3f}, por encima {np.mean(nuevo > m + h):.3f})")

# la anchura: intervalo de confianza para la media frente a predicción (normal, sigma = 1)
for n2 in [10, 100, 1000, 10000]:
    t = stats.t.ppf(0.975, n2 - 1)
    print(f"n = {n2:5d}: anchura del IC {2 * t / np.sqrt(n2):.3f}, de la predicción {2 * t * np.sqrt(1 + 1 / n2):.3f}")

One-sided intervals, joint regions and overlap

One-sided intervals. Sometimes only one bound matters: a maximum failure rate, a minimum accuracy. An upper bound of level 1−α1 - \alpha is a statistic UU with Pθ(θ≤U)≥1−α\Pr_\theta(\theta \le U) \ge 1 - \alpha; the equal-tailed two-sided interval is the intersection of two one-sided level-1−α/21 - \alpha/2 intervals, so it uses z1−α/2=1.96z_{1-\alpha/2} = 1.96, not z1−α=1.645z_{1-\alpha} = 1.645. Using a two-sided 95 % interval and looking only at one endpoint wastes precision: that endpoint is a 97.5 % bound, farther away than necessary if a 95 % bound was wanted. The rule of three is one-sided for the same reason.

Joint regions. Two marginal 95 % intervals do not form a joint 95 % region. If the two coverage events are independent, the rectangle covers 0.952=90.250.95^2 = 90.25 %. Beware: independent estimators alone are not enough. For a normal sample, Xˉ\bar X and S2S^2 are independent, but the tt interval for μ\mu also uses SS, so its coverage event depends on that of the χ2\chi^2 interval for σ2\sigma^2. Conditioning on V=(n−1)S2/σ2∼χn−12V = (n-1)S^2/\sigma^2 \sim \chi^2_{n-1}, exact rectangular coverage is

∫χn−1, α/22χn−1, 1−α/22[2Φ(tn−1, 1−α/2vn−1)−1]fχn−12(v) dv,\int_{\chi^2_{n-1,\,\alpha/2}}^{\chi^2_{n-1,\,1-\alpha/2}} \Big[2\Phi\Big(t_{n-1,\,1-\alpha/2}\sqrt{\tfrac{v}{n-1}}\Big) - 1\Big] f_{\chi^2_{n-1}}(v)\,dv,

which at n=15n = 15 is 90.6 % and tends to 90.25 % only as n→∞n \to \infty. For kk independent coverage events, 0.95k0.95^k: with 10 parameters, 60 %. Under dependence there is no formula, only Bonferroni’s bound: using level 1−α/k1 - \alpha/k for each interval guarantees at least joint 1−α1 - \alpha (union bound), with the usual conservatism. The dimension-aware solution is an ellipsoidal region (or profile likelihood with cutoff χd,1−α2/2\chi^2_{d,1-\alpha}/2): {θ:n(θ^−θ)⊤I(θ^)(θ^−θ)≤χd, 1−α2}\{\vb{\theta} : n(\hat{\vb{\theta}} - \vb{\theta})\T\mat{I}(\hat{\vb{\theta}})(\hat{\vb{\theta}} - \vb{\theta}) \le \chi^2_{d,\,1-\alpha}\}, with correct asymptotic coverage that respects parameter correlation.

[ ]Joint coverage of two marginal intervalsBrowser
import numpy as np
from scipy import stats, integrate

rng = np.random.default_rng(7)
n, R = 15, 100000
x = rng.normal(size=(R, n))                       # mu = 0, sigma^2 = 1
m, s2 = x.mean(axis=1), x.var(axis=1, ddof=1)

def cubre(nivel):
    a = (1 - nivel) / 2
    cm = np.abs(m) <= stats.t.ppf(1 - a, n - 1) * np.sqrt(s2 / n)
    cv = ((n - 1) * s2 / stats.chi2.ppf(1 - a, n - 1) <= 1) & (1 <= (n - 1) * s2 / stats.chi2.ppf(a, n - 1))
    return cm.mean(), cv.mean(), (cm & cv).mean()

for etiqueta, nivel in [("cada uno al 95 %", 0.95), ("Bonferroni: cada uno al 97.5 %", 0.975)]:
    cm, cv, cj = cubre(nivel)
    print(f"{etiqueta:30s} media {cm:.3f}  varianza {cv:.3f}  conjunto {cj:.3f}")

# cobertura conjunta exacta: se condiciona en V = (n-1) S^2 / sigma^2 ~ chi2_{n-1}
def conjunta_exacta(nivel):
    a, k = (1 - nivel) / 2, n - 1
    tq = stats.t.ppf(1 - a, k)
    f = lambda v: (2 * stats.norm.cdf(tq * np.sqrt(v / k)) - 1) * stats.chi2.pdf(v, k)
    return integrate.quad(f, stats.chi2.ppf(a, k), stats.chi2.ppf(1 - a, k))[0]

print(f"exacta: {conjunta_exacta(0.95):.4f} y {conjunta_exacta(0.975):.4f};  "
      f"si los sucesos fueran independientes: {0.95**2:.4f} y {0.975**2:.4f}")

Interval overlap. Overlapping 95 % intervals do not imply a nonsignificant difference. With two independent estimates of equal standard error ss, intervals overlap if ∣d∣<2⋅1.96 s=3.92 s\abs{d} \lt 2 \cdot 1.96\,s = 3.92\,s, but the difference test rejects at 5 % when ∣d∣>1.962 s=2.77 s\abs{d} > 1.96\sqrt 2\,s = 2.77\,s. For differences between 2.77 s2.77\,s and 3.92 s3.92\,s the intervals overlap and the difference is significant. The converse does not occur: non-overlap implies a significant difference. With equal standard errors, a simple rule that works is to use 83.4 % intervals (z=1.96/2z = 1.96/\sqrt 2), whose non-overlap is equivalent to the 5 % test; with different standard errors it is no longer exact, and the correct approach is to construct the difference interval directly. An exercise checks this with concrete numbers.

Using libraries

statsmodels.stats.proportion.proportion_confint implements proportion intervals ("normal", "wilson", "agresti_coull", "beta" for Clopper–Pearson, "jeffreys" and others), and scipy.stats.t.interval the tt interval. First we check agreement with our implementation, then use them in a real application: scanner detection rate evaluated on a small set of labeled cases. The numbers are illustrative.

[ ]Library intervals versus oursBrowser
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint

# nuestras implementaciones (recortadas a [0, 1]) frente a statsmodels, para varios (x, n)
Z = stats.norm.ppf(0.975)
def wilson(x, n):
    p = x / n
    c = (p + Z**2 / (2 * n)) / (1 + Z**2 / n)
    h = Z / (1 + Z**2 / n) * np.sqrt(p * (1 - p) / n + Z**2 / (4 * n**2))
    return c - h, c + h
def ac(x, n):
    nt = n + Z**2
    pt = (x + Z**2 / 2) / nt
    h = Z * np.sqrt(pt * (1 - pt) / nt)
    return max(pt - h, 0), min(pt + h, 1)
def cp(x, n):
    return (0.0 if x == 0 else stats.beta.ppf(0.025, x, n - x + 1)), (1.0 if x == n else stats.beta.ppf(0.975, x + 1, n - x))

maxdif = {"wilson": 0.0, "agresti_coull": 0.0, "beta": 0.0}
for n in [10, 50, 200]:
    for x in range(0, n + 1, max(1, n // 10)):
        for met, f in [("wilson", wilson), ("agresti_coull", ac), ("beta", cp)]:
            a = np.clip(f(x, n), 0, 1)
            b = np.clip(proportion_confint(x, n, alpha=0.05, method=met), 0, 1)
            maxdif[met] = max(maxdif[met], float(np.max(np.abs(np.array(a) - np.array(b)))))
print("máxima diferencia con statsmodels:", {k: f"{v:.1e}" for k, v in maxdif.items()})

# intervalo t frente a scipy
rng = np.random.default_rng(3)
y = rng.normal(5.0, 2.0, size=25)
m, se = y.mean(), y.std(ddof=1) / np.sqrt(len(y))
a = (m - stats.t.ppf(0.975, 24) * se, m + stats.t.ppf(0.975, 24) * se)
b = stats.t.interval(0.95, 24, loc=m, scale=se)
print("t a mano:", np.round(a, 4), "  scipy.stats.t.interval:", np.round(b, 4))

Now the application. A vulnerability scanner is evaluated on 120 labeled illustrative cases and detects 111. Which interval should be reported, and how many cases are needed to say something useful?

[ ]Scanner detection rate with 120 casesBrowser
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint

casos, detectados = 120, 111
print(f"tasa de detección observada: {detectados / casos:.3f}")
for met in ["normal", "wilson", "agresti_coull", "beta", "jeffreys"]:
    lo, hi = proportion_confint(detectados, casos, alpha=0.05, method=met)
    print(f"  {met:14s} [{lo:.3f}, {hi:.3f}]   anchura {hi - lo:.3f}")

# 1) ¿cuántos casos para un margen de ±2 puntos? n = z^2 p (1-p) / m^2 (peor caso p = 0.5, y con p = 0.9)
z = stats.norm.ppf(0.975)
for p in [0.5, 0.9]:
    print(f"margen ±2 puntos con p = {p}: n = {int(np.ceil(z**2 * p * (1 - p) / 0.02**2))}")

# 2) cero fallos: ¿cuántas pruebas hacen falta para acotar la tasa de fallo en el 1 % con el 95 %?
n_unilateral = int(np.ceil(np.log(0.05) / np.log(0.99)))       # (1 - 0.01)^n <= 0.05
n_bilateral = int(np.ceil(np.log(0.025) / np.log(0.99)))       # extremo superior de Clopper-Pearson bilateral
print(f"cero fallos: cota unilateral del 1 % con n = {n_unilateral}; cota superior del intervalo bilateral con n = {n_bilateral}")
print(f"regla del tres con n = 300: 3/300 = {3 / 300:.4f};  exacta: {1 - 0.05 ** (1 / 300):.4f}")
lo, hi = proportion_confint(0, 300, alpha=0.05, method="beta")
print(f"Clopper-Pearson bilateral con 0 fallos en 300: [{lo:.4f}, {hi:.4f}]")

Two conclusions. With 120 cases the Wilson interval is nearly 10 percentage points wide: not enough to distinguish 92 % from 88 %. For a margin of ±2\pm 2 points, around 2400 cases are needed in the worst case (p=1/2p = 1/2), and still around 865 if the rate is near 90 %. The rule of three has an uncomfortable corollary: “zero failures in 300 trials” does not prove a failure rate below 1 %; it bounds it below 1 % with 95 % confidence only if a one-sided bound is accepted (299 trials suffice). To get the upper endpoint of the two-sided Clopper–Pearson interval below 1 %, 368 are needed.

Common mistakes

Exercises

QuizInterpreting a 95 % interval
A study reports a 95 % confidence interval [0.12,0.31][0.12, 0.31] for the proportion pp of users who will respond to a campaign. Which statement is correct?
ProofDerive the Wilson interval
Prove: The Wilson interval is the set of p0p_0 values not rejected by the score test of H0:p=p0H_0: p = p_0 at level α\alpha. Solving the inequality gives p^+z22n±zp^(1−p^)n+z24n21+z2/n\dfrac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1 - \hat p)}{n} + \frac{z^2}{4n^2}}}{1 + z^2/n}.
0
Let X∼Bin⁡(n,p)X \sim \Bin(n, p), p^=X/n\hat p = X/n and z=z1−α/2z = z_{1-\alpha/2}. Under H0:p=p0H_0: p = p_0, Var⁡(p^)=p0(1−p0)/n\Var(\hat p) = p_0(1 - p_0)/n.

Step 1 of 4. What is the score test's acceptance region?

NumericThe rule of three
A system is tested on 300 independent cases with no observed failures. Using the rule of three, what is the approximate upper bound, as a proportion, on failure rate with 95 % confidence?
NumericCoverage of the sample range
You observe n=19n = 19 iid values from an unknown continuous distribution. What is the probability that a new observation falls between the minimum and maximum of the 19 values?
NumericAsymptotic coverage of the χ² interval
Data are exponential (kurtosis κ=9\kappa = 9), and the normality-based 95 % χ2\chi^2 variance interval is used. As n→∞n \to \infty, what does its coverage approach? Give a proportion.
NumericCases for a ±2 point margin
You want to estimate unknown accuracy with a 95 % Wald interval of half-width 0.02, with no prior idea of its value. How many cases are needed in the worst case (round up to an integer)?
QuizOverlapping intervals
Two models are evaluated on independent sets of 200 cases. A gets 160 correct (0.80) and B 176 (0.88). Their 95 % Wilson intervals are [0.739,0.850][0.739, 0.850] and [0.828,0.918][0.828, 0.918], which overlap. The standard error of their difference is 0.03640.0364. What is correct?
CodeClopper–Pearson with beta quantiles
Complete clopper_pearson(x, n, alpha=0.05) to return (lo, hi), the exact level-1 - alpha interval, using scipy.stats.beta quantiles. It must accept scalar x or an array of successes, returning 0 as the lower endpoint if x == 0 and 1 as the upper endpoint if x == n. Tests check known values, endpoints and, above all, that exact coverage never falls below `1 - alpha` over a grid of pp values.
import numpy as np
from scipy import stats

def clopper_pearson(x, n, alpha=0.05):
  """Devuelve (lo, hi) para x éxitos en n pruebas (x escalar o array)."""
  x = np.asarray(x, dtype=float)
  # tu código: cuantiles alpha/2 y 1 - alpha/2 de beta(x, n - x + 1) y beta(x + 1, n - x)
  # (cuidado con x = 0 y con x = n, donde un parámetro de la beta sería 0)
  return x / n, x / n
Shift+Enter to run
ProofInvariance of the profile likelihood interval
Prove: Let ψ\psi be the parameter of interest and ϕ=h(ψ)\phi = h(\psi) with hh strictly increasing and continuous. If [L,U][L, U] is the level-1−α1 - \alpha profile likelihood interval for ψ\psi, that for ϕ\phi is [h(L),h(U)][h(L), h(U)].
0
Let ℓp(ψ)=max⁡λℓ(ψ,λ)\ell_p(\psi) = \max_{\vb{\lambda}} \ell(\psi, \vb{\lambda}) be the profile of ψ\psi, and ℓ~p(ϕ)=max⁡λℓ(h−1(ϕ),λ)\tilde\ell_p(\phi) = \max_{\vb{\lambda}} \ell(h^{-1}(\phi), \vb{\lambda}) that of ϕ\phi. The cutoff is c=12χ1, 1−α2c = \tfrac12\chi^2_{1,\,1-\alpha} in both parameterizations.

Step 1 of 3. How are ℓ~p\tilde\ell_p and ℓp\ell_p related?

Summary

Key idea
A 95 % confidence interval is a procedure covering the parameter 95 % of the time, not a probability about the parameter; if exact (pivot), coverage holds for all nn, while if approximate (Wald), measure it by simulation and inspect both tails, because with discrete or skewed data or near boundaries reality differs from the promise.
  • Definition. Pθ(L≤θ≤U)≥1−α\Pr_\theta(L \le \theta \le U) \ge 1 - \alpha for every θ\theta. The interval is random; the parameter is fixed. Nominal is not actual: procedure coverage must be measured, in each tail.
  • Pivots. A data-and-parameter function with known distribution gives exact intervals: tt for the mean, χ2\chi^2 for variance. The tt pivot withstands non-normality at a rate depending on skewness; χ2\chi^2 depends on kurtosis and its error does not disappear with nn.
  • Wald. θ^±z SE^\hat\theta \pm z\,\widehat{\mathrm{SE}} has correct but nonuniform asymptotic coverage and depends on parameterization. Inverting a test instead of solving with estimated standard error (Wilson, likelihood) almost always fixes this.
  • Proportion. Wald collapses near 0 and 1 for all nn (with p=λ/np = \lambda/n, coverage is bounded by 1−(1−λ/n)n≈1−e−λ1 - (1 - \lambda/n)^n \approx 1 - e^{-\lambda}). Wilson and Agresti–Coull oscillate around the level. Clopper–Pearson never falls below level and overcovers. Zero failures in nn trials: 95 % bound 3/n3/n.
  • Profile likelihood. Cutting log-likelihood at −χ1,1−α2/2-\chi^2_{1,1-\alpha}/2 yields an asymmetric interval invariant under monotone reparameterization, with better coverage than Wald when the normal approximation is poor.
  • Prediction. Confidence intervals shrink like 1/n1/\sqrt n; prediction intervals for the next observation tend to fixed width 2zσ2z\sigma. Without assuming the law, [X(j),X(n+1−j)][X_{(j)}, X_{(n+1-j)}] covers exactly (n+1−2j)/(n+1)(n + 1 - 2j)/(n + 1) (requiring n≥39n \ge 39 for 95 %): the seed of conformal prediction.
  • Multiple parameters. Two marginal 95 % intervals do not form a 95 % region. Interval overlap does not decide significance: construct the difference interval.