AI Wiki中文/EN

Confidence intervals

置信区间

Construct interval procedures, derive Wilson bounds, and enumerate actual coverage instead of trusting a nominal percentage.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Twenty passes are not a guarantee

A model passes all twenty independent test cases. The observed success rate is 100%. Would you promise that it will never fail? A point estimate alone cannot answer how much uncertainty remains. Under an i.i.d. Bernoulli model for failures, a two-sided 95% Wilson interval for the failure probability is approximately [0, 0.1611]. Zero observed failures can coexist with substantial uncertainty.

A confidence interval is a rule for turning random data into a range for a fixed parameter. Its confidence level describes the rule’s repeated-sampling coverage under specified assumptions. It does not automatically assign a probability distribution to that parameter after seeing one dataset. MIT 18.05, Class 23, interpretation

Imagine repeatedly drawing a fresh set of twenty cases from the same population and applying the same rule. The intervals move; the population’s failure probability stays fixed. There is a further catch: Wilson is an approximate method. The label “95%” is its nominal level, not a promise of exactly 95% coverage at every sample size and probability. We will compute the actual coverage instead of relying on the label.

Build a rule, then ask what it covers

Let XX denote the whole random dataset and C(X)=[L(X),U(X)]C(X)=[L(X),U(X)]. A procedure with confidence level at least 1−α1-\alpha satisfies

Pr⁡θ{θ∈C(X)}≥1−α∀θ∈Θ.\Pr_\theta\{\theta\in C(X)\}\geq 1-\alpha\quad\forall\theta\in\Theta.

Here Θ is the assumed parameter space; the subscript specifies which data-generating distribution supplies the probability. Exact equality is possible in some continuous models; discrete observations often produce conservative intervals with coverage above the nominal level. Once we observe x, both endpoints are numbers. The coverage definition alone does not give Pr⁡(θ∈C(x)∣x)\Pr(\theta\in C(x)\mid x). A Bayesian credible interval instead uses a posterior distribution under a specified prior and likelihood.

For independent Xi∼N(μ,σ2)X_i\sim N(\mu,\sigma^2) with known positive σ, the pivot Z=(X‾−μ)/(σ/n)Z=(\overline X-\mu)/(\sigma/\sqrt n) has a standard normal distribution that does not depend on μ. Define z=Φ−1(1−α/2)z=\Phi^{-1}(1-\alpha/2). Rearranging −z≤Z≤z-z\leq Z\leq z gives

C(X)=[X‾−zσn, X‾+zσn].C(X)=\left[\overline X-z\frac{\sigma}{\sqrt n},\ \overline X+z\frac{\sigma}{\sqrt n}\right].

This interval has exact nominal coverage under those assumptions. If σ is unknown and estimated by the sample standard deviation S, the corresponding exact normal-data interval uses the tn−1t_{n-1} quantile and S/nS/\sqrt n, for n≥2n\geq2. Merely replacing σ with S while keeping the normal quantile loses exactness. For non-normal data, large-sample justification needs its own conditions. MIT 18.05, Class 23, Sections 3.1–3.2

For a Bernoulli proportion, let K∼Binomial⁡(n,p)K\sim\operatorname{Binomial}(n,p) and p^=K/n\widehat p=K/n. A simple Wald interval substitutes p^\widehat p into its own estimated standard error. At K=0, this produces [0,0], which illustrates its boundary failure. Wilson instead keeps each candidate p inside the variance while inverting the approximate score-test acceptance inequality:

n(p^−p)2p(1−p)≤z2,0<p<1.\frac{n(\widehat p-p)^2}{p(1-p)}\leq z^2,\qquad 0<p<1.

Multiply through and collect powers of p:

(n+z2)p2−(2np^+z2)p+np^2≤0.(n+z^2)p^2-(2n\widehat p+z^2)p+n\widehat p^2\leq0.

Solving this quadratic, and extending to the appropriate endpoints of [0,1], yields

p^+z2/(2n) ± zp^(1−p^)/n+z2/(4n2)1+z2/n.\frac{\widehat p+z^2/(2n)\ \pm\ z\sqrt{\widehat p(1-\widehat p)/n+z^2/(4n^2)}}{1+z^2/n}.

The shifted center and nonzero boundary width emerge from the algebra. They are not an arbitrary repair after seeing the data. The test still uses a normal approximation, so its inversion still needs a finite-sample coverage check. NIST e-Handbook, proportion confidence intervals

Measure coverage without Monte Carlo noise

For fixed n there are only n+1 possible counts. Compute each interval, keep the counts whose intervals contain the chosen p, and add their binomial probabilities:

coverage⁡(p)=∑k=0n1{L(k)≤p≤U(k)}(nk)pk(1−p)n−k.\operatorname{coverage}(p)=\sum_{k=0}^{n}\mathbf1\{L(k)\leq p\leq U(k)\}\binom nkp^k(1-p)^{n-k}.

The program uses exact rational probability weights and floating-point Wilson endpoints. Thus there is no sampling noise, but a parameter within rounding distance of an endpoint needs higher-precision endpoint evaluation. Explicit endpoint cases avoid losing coverage at p=0 or p=1 through a tiny rounding error.

import math
from fractions import Fraction as F
from statistics import NormalDist

def wilson(k, n, alpha=.05):
    if type(n) is not int or not 1<=n<=500 or type(k) is not int or not 0<=k<=n:
        raise ValueError("integer 1<=n<=500 and 0<=k<=n required")
    if not isinstance(alpha,(int,float)) or not math.isfinite(alpha) or not 1e-8<=alpha<=.99:
        raise ValueError("alpha must be finite and in [1e-8,.99]")
    z = NormalDist().inv_cdf(1-alpha/2)
    p = k/n
    denominator = 1+z*z/n
    center = (p+z*z/(2*n))/denominator
    half = z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/denominator
    lower = 0. if k==0 else max(0.,center-half)
    upper = 1. if k==n else min(1.,center+half)
    return lower,upper

def coverage(n, p, alpha=.05):
    if not isinstance(p,F) or not 0<=p<=1:
        raise ValueError("p must be a Fraction in [0,1]")
    wilson(0,n,alpha)
    total = F(0)
    for k in range(n+1):
        lower,upper = wilson(k,n,alpha)
        if F(lower)<=p<=F(upper):
            total += math.comb(n,k)*p**k*(1-p)**(n-k)
    return total

lo,hi = wilson(0,20)
assert lo==0 and abs(hi-.16112515805281927)<1e-14
assert wilson(20,20)[1]==1
for p in [F(1,100),F(1,20),F(1,10),F(1,2)]:
    print(float(p),round(float(coverage(20,p)),6))
assert abs(float(coverage(20,F(1,20)))-.9245163262115035)<1e-14
assert coverage(20,F(0))==coverage(20,F(1))==1
True p, with n=20Coverage of nominal 95% Wilson intervals
0.010.983141
0.050.924516
0.100.956826
0.500.958611

At p=0.05, the accepted counts are 0, 1 and 2. Their probability totals about 92.45%, below the nominal 95%. A single interval formula can overcover at one parameter and undercover at another. Averaging coverage across chosen parameter values would be a different quantity and would require specifying those weights.

A Wilson interval requires a constant number of scalar operations. The coverage routine makes n+1 interval evaluations and n+1 binomial-weight evaluations; each exact combinatorial coefficient and rational power has additional integer-arithmetic cost. The n cap keeps this teaching enumeration small. For large n, use tested distribution routines with careful tail arithmetic.

The sampling design is part of the interval

The “twenty tests” example assumes independent cases from the population being described. Twenty paraphrases of one question can share a failure mode. Treating them as twenty independent observations can make uncertainty look smaller than it is. An interval for benchmark accuracy also says nothing by itself about a different deployment population.

An exact Clopper–Pearson interval for a binomial p inverts binomial tail probabilities, retaining at least nominal coverage under the binomial assumptions; discreteness commonly makes it conservative. That is a different construction from Wilson. “Exact” refers to the probability model and coverage calculation, not immunity to biased data. NIST exact binomial confidence limits

A confidence interval for a population mean is not a prediction interval for a new observation. Individual observations have their own variability even when the mean is well estimated. Repeatedly checking a fixed-sample interval and stopping when it looks favorable can also change coverage; the fixed-n proof does not cover that stopping rule.

If m separately constructed intervals each fail with probability at most α/m, the union bound gives simultaneous coverage at least 1−α, without requiring independence between the intervals. This Bonferroni argument may be conservative. Using m unadjusted 95% intervals does not generally give a 95% probability that all m cover together.

Identify the repeated experiment

  1. Twenty independent trials have zero failures. Is [0,0] a reasonable general-purpose 95% interval for the failure probability? Answer: No. For any positive p it fails whenever K=0; at p=0.05 that event has probability 0.9520≈0.35850.95^{20}\approx0.3585. A zero estimated standard error is not proof of zero uncertainty.
  2. Under the known-σ normal model, how many observations are needed to halve an interval’s width at the same confidence level? Answer: Four times as many, because width is proportional to 1/n1/\sqrt n.
  3. Which part is random in Pr⁡θ{θ∈C(X)}\Pr_\theta\{\theta\in C(X)\}? Answer: X and therefore the interval. The frequentist parameter θ is fixed in this probability statement.
  4. Ten intervals must cover simultaneously with probability at least 0.95. What individual error bound suffices by the union bound? Answer: At most 0.005 per interval. This requires each individual coverage guarantee to be valid; assigning a label to an approximate procedure is insufficient.

Read coverage claims as conditional statements

When a paper reports an interval, record the estimand, observational unit, sampling assumptions, construction, and whether the level is exact, asymptotic, or empirically assessed. A narrow interval can estimate the wrong target very precisely.

Continue to Bootstrap to examine estimated sampling distributions when simple pivots are unavailable, and to posterior prediction to separate uncertainty about parameters from uncertainty about future outcomes. The useful question is not which school “owns” uncertainty; it is which probability statement the available evidence supports.

Make a prediction, then check

What is the actual coverage of nominal 95% Wilson intervals at n=20 and p=0.05?

Choose one answer

Learning objectives

  • Distinguish nominal confidence, actual coverage, credible intervals and prediction intervals.
  • Derive Wilson intervals from a score inequality and enumerate coverage with binomial weights.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to Probability and Statistics — Statistics Reading, Classes 22–24
    Jeremy Orloff; Jonathan Bloom; MIT OpenCourseWare · 2022
  2. NIST/SEMATECH e-Handbook — 7.2.4.1 Confidence intervals for proportions
    NIST; SEMATECH
  3. Dataplot Reference Manual — Exact Binomial Confidence Limits
    NIST

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Independently checked Wilson endpoints and interior grids against the score inequality; enumerated ordered Bernoulli sequences for n=1 through 8 to verify exact coverage weights and nominal-versus-actual differences.
  • Verified the known-standard-deviation normal pivot, conditions for the unknown-standard-deviation t interval, boundary inputs and floating endpoint limits; did not label sample standard deviation S as variance.
  • Another agent recomputed the four coverage rates using 70-digit Decimal quadratic roots and exact probability weights, agreeing with the article and parent enumeration tests.
  • The parent executed all 30 new checks and all 55 combined probability/inference tests; bilingual code, display equations, six main anchors, citations and four answered exercises were additionally compared.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.