Algorithmcore
Wilson score interval
Also called Wilson interval.
A confidence interval for a binomial p that inverts the score test by solving a quadratic. Coverage is near 1 - alpha on average but dips below it for some p.
- Time
- Θ(1) worst · best
- Space
- Θ(1) extra
- Where
- n = the number of trials
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Edwin B. Wilson, 1927
The Wilson score interval is a confidence interval for the success probability of a binomial distribution. It is the set of that the two-sided score test, the z-test for one proportion with the null variance , does not reject. That set is the solution of a quadratic inequality in , so the interval has a closed form. Its center is pulled from toward , it never leaves , and it has positive length when or . Its coverage is not guaranteed: it is close to on average over , but it dips below for many , and to about near the ends at the 95% level for every .
In plain words
The usual quick interval takes the observed rate and adds and subtracts about two standard errors, with the standard error computed from the observed rate. That fails badly when the rate is near 0 or 1, or when there are few trials. With 0 successes it gives an interval of length zero.
Wilson's idea is to ask, for each candidate rate, whether the observed count is within about two standard errors of what that candidate predicts, with the standard error computed from the candidate. The candidates that pass form the interval. The answer comes from solving a quadratic equation, so no search is needed. The interval is a little shifted toward one half, which is what makes it behave well. It is usually shorter than the exact Clopper-Pearson interval, but it does not promise its level at every rate.
The problem
Input. A count from with , and a level .
Output. An interval .
Construction. Inversion of the score test, by test-interval duality. Let be the upper point of the standard normal law, . The interval is
Coverage. Asymptotic and not uniform: for each fixed the coverage tends to as (by the central limit theorem), but for every there are where it is well below . The coverage is marginal over at a fixed .
The algorithm
WILSON(x, n, α)- 1
z ← the upper α/2 point of N(0, 1) - 2
c ← (x + z²/2) / (n + z²) - 3
h ← z / (n + z²) · sqrt(x (n - x) / n + z²/4) - 4
U ← c + h ▷ U = 1 exactly when x = n - 5
L ← (x² / n) / ((n + z²) · U) ▷ product of the roots over U - 6
return [L, U]
Line L1 uses statistics.NormalDist().inv_cdf. Line L5 uses Vieta's formula: the two roots of have the product . The direct form subtracts two close numbers when is small. The loss is only a few digits at the usual levels, but at the direct form gave a nonzero lower end, up to about in size, for 545 of the values at , 144 of them negative, and a nonzero one for 587 values at , 503 of them negative. Line L5 gives exactly at .
Example
Take , and , so .
- Line L2: .
- Line L3: .
- Line L4: .
- Line L5: .
So the 95% Wilson interval is , against for Clopper-Pearson and for the Wald interval . At each end the score statistic is : for example at , .
At , and for . At , and .
Measured coverage. The coverage at a fixed is the finite sum , computed exactly, with no simulation. On the grid at :
| smallest coverage on the grid (at ) | mean coverage | share of the grid below 0.95 | |
|---|---|---|---|
| 10 | 0.8424 (0.017) | 0.9542 | 44% |
| 20 | 0.8516 (0.008) | 0.9532 | 40% |
| 50 | 0.8605 (0.003) | 0.9517 | 40% |
The mean is close to 0.95, but the coverage falls below 0.95 for a large share of and has deep dips near the ends. A grid misses the exact worst point, which the theorem below locates.
Correctness
The full proof is in proofs/correctness.md. Expanding gives a convex quadratic in whose discriminant is , so the acceptance set is the interval between its roots . The quadratic is non-negative at and , so both roots lie in , and it is non-positive at , so the interval contains .
What is proved about coverage. For fixed , the coverage is for the standardized count , which tends to . Near the ends this fails for every : let be the smaller root of , which is at . For , only gives an interval that contains , so the coverage is exactly , and it approaches as rises to . For this is , slightly below the grid minimum in the table. The proof holds for .
What is only measured. The mean coverage near and the share of below come from the exact sums in the table, not from a theorem. Contrast the Clopper-Pearson interval, whose coverage of at least at every is proved.
Proof: The Wilson interval is the set of p that the score test accepts, and its coverage dips below 0.84 for every nfull
Let with , observed value , and let be the upper point of the standard normal law. The two-sided score test of accepts when . The score of the binomial log-likelihood at is and the Fisher information is , so this is the squared score statistic compared with .
Claim 1 (the acceptance set is the interval of the page). For , the score test accepts if and only if , where
Proof. Expand the acceptance condition and divide by :
is a quadratic with positive leading coefficient. Its discriminant is
so has two real roots , and exactly between them.
Claim 2 (the ends lie in and contain ). and , and the vertex lies in . A convex quadratic that is non-negative at and at , with its vertex between them, has both roots in . Also , so . The root occurs exactly when , and the root exactly when .
Claim 3 (the code computes these roots). Lines L2 and L3 compute and , and line L4 sets , or exactly when . By Vieta's formulas the product of the roots is , so line L5 computes . Since , the division is safe. This form has no subtraction, so it does not lose digits when and are close, and it gives exactly when .
Claim 4 (asymptotic coverage at a fixed ). For fixed , the coverage tends to as .
Proof. By Claim 1, with . By the central limit theorem, converges in distribution to , and the normal law has no atom at , so .
The convergence is not uniform in . The next claim gives a bound that holds for every .
Claim 5 (a dip near the ends, for every ). Let , and let be the smaller root of . For every and every with , the interval covers only when , so . Hence
For , and .
Proof. Write and , so . Since and , the smaller root satisfies , and on . By Claim 1, the interval for covers if and only if .
- does not cover . Since , . Since , .
- covers . The condition is . Since , it suffices that , that is . A direct expansion gives , which is at most when , that is when , which holds for . Then is not in the region where , so .
So . Letting rise to gives the first bound, and for gives the second.
What is proved and what is measured. Claims 1 to 5 are proved. The mean coverage near , the place of the smallest coverage on a grid, and the share of with coverage below are measured on the page by exact binomial sums over a grid of . They are not theorems.
Cost. Lines L1 to L6 do a fixed number of operations, one square root and one normal quantile, so the time and space are .
Complexity
The interval costs a fixed number of arithmetic operations, one square root and one normal quantile: time and space, independent of . Clopper-Pearson, by contrast, needs a root search over binomial tails or Beta quantiles.
Properties
- Inside . Both ends lie in for every , with no truncation needed.
- Never degenerate. The length is positive for every , including and .
- Shrunk center. The center is a weighted mean of and . For 95% it is close to adding two successes and two failures.
- Symmetry. .
- Monotone in . Both ends increase with .
- Not equal-tailed. The two miss probabilities can be very unequal near the ends; see Pitfalls.
- Shorter than Clopper-Pearson. In the examples above it is contained in the Clopper-Pearson interval, and its mean coverage is closer to .
Variants and improvements
- Continuity correction. Replace by in the inequality. The coverage rises toward that of Clopper-Pearson and the interval gets wider.
- Agresti-Coull interval. Use and , the Wilson center, with the simple width . It contains the Wilson interval and is easy to compute by hand; for 95% it is the "add two successes and two failures" rule.
- Jeffreys interval. The equal-tailed interval of the posterior, with the frequentist coverage studied by Brown, Cai and DasGupta. It is recommended with Wilson for small .
- Modified ends. Brown, Cai and DasGupta (2001) suggest replacing the Wilson lower end for the smallest positive (up to 2 or 3, depending on ) by a one-sided Poisson-based bound, which removes the deepest dips near ; the upper end changes in the same way by symmetry.
- Wald interval. inverts the Wald test instead of the score test. Its coverage is erratic even for large , and it collapses to a point at and . Avoid it.
- Two samples and other models. The same inversion of the score test gives intervals for a difference of proportions and for a Poisson rate.
When to use it
Use it as the default interval for one proportion when an average coverage close to and a short interval matter more than a guarantee at every , and for any , including small . Use Clopper-Pearson when a guarantee at every is required. If may be very close to 0 or 1 and the lower end matters, use the modified ends or an exact interval.
Pitfalls
- Average is not a guarantee. "Coverage about 95%" is an average over . At just below the 95% interval covers with probability below , for every .
- Uneven tails. Near almost all misses come from the interval lying above . Do not use one end of a two-sided Wilson interval as a one-sided bound at level without checking.
- The direct lower root. loses digits for small and can be slightly negative or nonzero at . Use line L5.
- Wrong variance. The score test uses the variance at the candidate , not at . Using gives the Wald interval.
- Dependence and overdispersion. As for every binomial method, clustered trials make the true variance larger, and the coverage falls.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilson-score-interval/. The authors are listed in prov/H3CD21.jsonl.
import math
from statistics import NormalDist
def wilson_score_interval(x: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
"""The Wilson score interval [L, U] for a binomial p at nominal level 1 - alpha.
[L, U] is the set of p with (x - n p)^2 <= z^2 n p (1 - p), where z is the
upper alpha/2 point of the standard normal: the values that the two-sided
score test does not reject. The upper root is computed as center plus
half-width, and the lower root as (x^2 / n) / ((n + z^2) U), the product of
the roots divided by U, which avoids cancellation when x is small.
"""
if not (isinstance(x, int) and isinstance(n, int)) or n < 1 or not 0 <= x <= n:
raise ValueError("need integers with 0 <= x <= n and n >= 1")
if not 0.0 < alpha < 1.0:
raise ValueError("alpha must be in (0, 1)")
z = NormalDist().inv_cdf(1.0 - alpha / 2) # @line L1
z2 = z * z
center = (x + z2 / 2) / (n + z2) # @line L2
half = z / (n + z2) * math.sqrt(x * (n - x) / n + z2 / 4) # @line L3
# p = 1 is a root exactly when x = n; set it exactly instead of 1 +- rounding.
upper = 1.0 if x == n else min(1.0, center + half) # @line L4
lower = (x * x / n) / ((n + z2) * upper) # @line L5
return lower, upper # @line L6
test_wilson_score_interval.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilson-score-interval/. The authors are listed in prov/H3CD21.jsonl.
import math
from fractions import Fraction
from statistics import NormalDist
import pytest
from wilson_score_interval import wilson_score_interval
Z = NormalDist().inv_cdf(0.975)
def test_page_examples() -> None:
assert wilson_score_interval(3, 10) == pytest.approx((0.107791, 0.603222), abs=1e-6)
assert wilson_score_interval(7, 20) == pytest.approx((0.181192, 0.567146), abs=1e-6)
assert wilson_score_interval(0, 10) == (0.0, pytest.approx(Z * Z / (10 + Z * Z), abs=1e-15))
lo, hi = wilson_score_interval(10, 10)
assert hi == 1.0 and lo == pytest.approx(10 / (10 + Z * Z), abs=1e-15)
def test_ends_solve_the_score_equation() -> None:
# (x - n p)^2 = z^2 n p (1 - p) at both ends, checked in exact arithmetic on the floats.
z2 = Fraction(Z) ** 2
for n in (1, 2, 7, 30, 1000, 10**9):
for x in sorted({0, 1, 2, n // 3, n // 2, n - 1, n}):
if not 0 <= x <= n:
continue
for p in wilson_score_interval(x, n):
q = Fraction(p)
residual = (x - n * q) ** 2 - z2 * n * q * (1 - q)
scale = x * x + z2 * n + 1
assert abs(residual) / scale < 1e-12, (x, n, p)
def test_small_x_has_no_cancellation() -> None:
# The naive center - half loses all digits here; the product form keeps them.
n = 10**12
lo, hi = wilson_score_interval(1, n)
z2 = Z * Z
product = (1 / n) / (n + z2)
assert lo * hi == pytest.approx(product, rel=1e-14)
assert lo > 0
def test_inverts_the_score_test() -> None:
for n in (5, 12, 40):
for x in range(n + 1):
lo, hi = wilson_score_interval(x, n)
for k in range(1, 1000):
p0 = k / 1000
if min(abs(p0 - lo), abs(p0 - hi)) < 1e-9:
continue
accept = abs(x - n * p0) <= Z * math.sqrt(n * p0 * (1 - p0))
assert accept == (lo <= p0 <= hi), (n, x, p0)
def test_symmetry_and_order() -> None:
for n in (1, 9, 50):
rows = [wilson_score_interval(x, n, 0.1) for x in range(n + 1)]
for x in range(n + 1):
lo, hi = rows[x]
assert 0.0 <= lo < x / n + 1e-15 or x == 0
assert lo <= x / n <= hi
assert lo == pytest.approx(1 - rows[n - x][1], abs=1e-14)
assert all(a[0] < b[0] and a[1] < b[1] for a, b in zip(rows, rows[1:]))
def exact_coverage(n: int, p: float, rows: list[tuple[float, float]]) -> float:
w = [math.comb(n, k) * p**k * (1 - p) ** (n - k) for k in range(n + 1)]
return math.fsum(w[x] for x in range(n + 1) if rows[x][0] <= p <= rows[x][1])
def test_measured_coverage_on_a_grid() -> None:
# Coverage is not guaranteed; it is measured by exact binomial sums.
table = {10: (0.8424, 0.017), 20: (0.8516, 0.008), 50: (0.8605, 0.003)}
for n, (minimum, where) in table.items():
rows = [wilson_score_interval(x, n) for x in range(n + 1)]
grid = [k / 1000 for k in range(1, 1000)]
cover = [exact_coverage(n, p, rows) for p in grid]
i = min(range(len(grid)), key=cover.__getitem__)
assert cover[i] == pytest.approx(minimum, abs=1e-4)
assert grid[i] == where
mean = sum(cover) / len(cover)
assert 0.945 < mean < 0.96
assert sum(c < 0.95 for c in cover) > 300
def test_proved_dip_near_zero() -> None:
# Just below p = lam*/n, only x = 0 covers p, so the coverage is (1 - p)^n < exp(-lam*).
z2 = Z * Z
lam = ((2 + z2) - math.sqrt((2 + z2) ** 2 - 4)) / 2
assert math.exp(-lam) == pytest.approx(0.83818, abs=1e-5)
for n in (1, 2, 5, 10, 37, 100, 1000):
p = lam / n * (1 - 1e-9)
rows = [wilson_score_interval(x, n) for x in range(n + 1)]
assert [x for x in range(n + 1) if rows[x][0] <= p <= rows[x][1]] == [0]
assert exact_coverage(n, p, rows) == pytest.approx((1 - p) ** n, rel=1e-12)
assert exact_coverage(n, p, rows) < math.exp(-lam)
def test_errors() -> None:
for bad in ((3, 2), (-1, 5), (0, 0)):
with pytest.raises(ValueError):
wilson_score_interval(*bad)
with pytest.raises(ValueError):
wilson_score_interval(1, 5, 0.0)
History
Edwin B. Wilson (1927) observed that the usual interval treats the estimate as if it were the true value in the variance, and solved for instead. The interval was little used for decades. Agresti and Coull (1998) showed by exact coverage computations that it beats both the Wald and the Clopper-Pearson intervals as a practical choice, and Brown, Cai and DasGupta (2001) showed that the Wald interval's coverage oscillates even for large and recommended Wilson or Jeffreys for small .
References
- Edwin B. Wilson, Probable inference, the law of succession, and statistical inference, Journal of the American Statistical Association 22(158), 1927, pp. 209 to 212
- Lawrence D. Brown, T. Tony Cai and Anirban DasGupta, Interval estimation for a binomial proportion, Statistical Science 16(2), 2001, pp. 101 to 133 (the oscillating coverage of the Wald interval and the comparison with the Wilson, Agresti-Coull and Jeffreys intervals)
- Alan Agresti and Brent A. Coull, Approximate is better than "exact" for interval estimation of binomial proportions, The American Statistician 52(2), 1998, pp. 119 to 126 (the score interval and the add two successes and two failures interval)
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Section 1.4 (the Wald, score and likelihood-ratio intervals for a binomial parameter)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H3CD21 Edit this page History Report an error Markdown