Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
Origin
Edwin B. Wilson, 1927

The Wilson score interval is a confidence interval for the success probability pp of a binomial distribution. It is the set of p0p_0 that the two-sided score test, the z-test for one proportion with the null variance p0(1−p0)/np_0(1 - p_0)/n, does not reject. That set is the solution of a quadratic inequality in p0p_0, so the interval has a closed form. Its center is pulled from p^=x/n\hat p = x/n toward 1/21/2, it never leaves [0,1][0, 1], and it has positive length when x=0x = 0 or x=nx = n. Its coverage is not guaranteed: it is close to 1−α1 - \alpha on average over pp, but it dips below 1−α1 - \alpha for many pp, and to about 0.840.84 near the ends at the 95% level for every nn.

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 x∈{0,…,n}x \in \{0, \ldots, n\} from X∼Binomial(n,p)X \sim \text{Binomial}(n, p) with n≥1n \ge 1, and a level α∈(0,1)\alpha \in (0, 1).

Output. An interval [L,U]⊆[0,1][L, U] \subseteq [0, 1].

Construction. Inversion of the score test, by test-interval duality. Let z=z1−α/2z = z_{1 - \alpha/2} be the upper α/2\alpha/2 point of the standard normal law, z0.975≈1.959964z_{0.975} \approx 1.959964. The interval is

{p:(x−np)2≤z2 np(1−p)}=[ c−h,  c+h ],\big\{ p : (x - np)^2 \le z^2\, n p (1 - p) \big\} = [\,c - h,\; c + h\,],
c=x+z2/2n+z2,h=zn+z2x(n−x)n+z24.c = \frac{x + z^2/2}{n + z^2}, \qquad h = \frac{z}{n + z^2} \sqrt{\frac{x(n - x)}{n} + \frac{z^2}{4}}.

Coverage. Asymptotic and not uniform: for each fixed p∈(0,1)p \in (0, 1) the coverage tends to 1−α1 - \alpha as n→∞n \to \infty (by the central limit theorem), but for every nn there are pp where it is well below 1−α1 - \alpha. The coverage is marginal over XX at a fixed pp.

The algorithm

  1. WILSON(x, n, α)
  2. 1z ← the upper α/2 point of N(0, 1)
  3. 2c ← (x + z²/2) / (n + z²)
  4. 3h ← z / (n + z²) · sqrt(x (n - x) / n + z²/4)
  5. 4U ← c + h ▷ U = 1 exactly when x = n
  6. 5L ← (x² / n) / ((n + z²) · U) ▷ product of the roots over U
  7. 6return [L, U]

Line L1 uses statistics.NormalDist().inv_cdf. Line L5 uses Vieta's formula: the two roots of (n+z2)p2−(2x+z2)p+x2/n(n + z^2) p^2 - (2x + z^2) p + x^2/n have the product (x2/n)/(n+z2)(x^2/n)/(n + z^2). The direct form c−hc - h subtracts two close numbers when xx is small. The loss is only a few digits at the usual levels, but at x=0x = 0 the direct form gave a nonzero lower end, up to about 5.6×10−175.6 \times 10^{-17} in size, for 545 of the values n=1,…,1999n = 1, \ldots, 1999 at α=0.05\alpha = 0.05, 144 of them negative, and a nonzero one for 587 values at α=0.32\alpha = 0.32, 503 of them negative. Line L5 gives L=0L = 0 exactly at x=0x = 0.

Example

Take n=10n = 10, x=3x = 3 and α=0.05\alpha = 0.05, so z2=3.8415z^2 = 3.8415.

  • Line L2: c=(3+1.9207)/13.8415=0.35551c = (3 + 1.9207)/13.8415 = 0.35551.
  • Line L3: h=(1.95996/13.8415)2.1+0.96037=0.14160×1.74939=0.24771h = (1.95996/13.8415) \sqrt{2.1 + 0.96037} = 0.14160 \times 1.74939 = 0.24771.
  • Line L4: U=0.60322U = 0.60322.
  • Line L5: L=0.9/(13.8415×0.60322)=0.10779L = 0.9/(13.8415 \times 0.60322) = 0.10779.

So the 95% Wilson interval is [0.1078,0.6032][0.1078, 0.6032], against [0.0667,0.6525][0.0667, 0.6525] for Clopper-Pearson and [0.0160,0.5840][0.0160, 0.5840] for the Wald interval p^±zp^(1−p^)/n\hat p \pm z \sqrt{\hat p (1 - \hat p)/n}. At each end the score statistic is ±z\pm z: for example at p=0.60322p = 0.60322, (3−6.0322)/10×0.60322×0.39678=−1.95996(3 - 6.0322)/\sqrt{10 \times 0.60322 \times 0.39678} = -1.95996.

At x=0x = 0, L=0L = 0 and U=z2/(n+z2)=0.2775U = z^2/(n + z^2) = 0.2775 for n=10n = 10. At x=nx = n, U=1U = 1 and L=n/(n+z2)=0.7225L = n/(n + z^2) = 0.7225.

Measured coverage. The coverage at a fixed pp is the finite sum C(p)=∑x:L(x)≤p≤U(x)(nx)px(1−p)n−xC(p) = \sum_{x : L(x) \le p \le U(x)} \binom{n}{x} p^x (1-p)^{n-x}, computed exactly, with no simulation. On the grid p=0.001,…,0.999p = 0.001, \ldots, 0.999 at α=0.05\alpha = 0.05:

nn smallest coverage on the grid (at pp) 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 pp 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 (x−np)2≤z2np(1−p)(x - np)^2 \le z^2 np(1 - p) gives a convex quadratic in pp whose discriminant is 4z2(x(n−x)/n+z2/4)>04z^2(x(n - x)/n + z^2/4) > 0, so the acceptance set is the interval between its roots c∓hc \mp h. The quadratic is non-negative at p=0p = 0 and p=1p = 1, so both roots lie in [0,1][0, 1], and it is non-positive at x/nx/n, so the interval contains p^\hat p.

What is proved about coverage. For fixed p∈(0,1)p \in (0, 1), the coverage is P(∣Zn∣≤z)P(\lvert Z_n \rvert \le z) for the standardized count ZnZ_n, which tends to 1−α1 - \alpha. Near the ends this fails for every nn: let λ∗\lambda^* be the smaller root of λ2−(2+z2)λ+1=0\lambda^2 - (2 + z^2)\lambda + 1 = 0, which is 0.1765250.176525 at α=0.05\alpha = 0.05. For 0<p<λ∗/n0 < p < \lambda^*/n, only x=0x = 0 gives an interval that contains pp, so the coverage is exactly (1−p)n(1 - p)^n, and it approaches (1−λ∗/n)n<e−λ∗=0.8382(1 - \lambda^*/n)^n < e^{-\lambda^*} = 0.8382 as pp rises to λ∗/n\lambda^*/n. For n=10n = 10 this is 0.83690.8369, slightly below the grid minimum in the table. The proof holds for α≤0.38\alpha \le 0.38.

What is only measured. The mean coverage near 1−α1 - \alpha and the share of pp below 1−α1 - \alpha come from the exact sums in the table, not from a theorem. Contrast the Clopper-Pearson interval, whose coverage of at least 1−α1 - \alpha at every pp 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 X∼Binomial(n,p)X \sim \text{Binomial}(n, p) with n≥1n \ge 1, observed value xx, and let z=z1−α/2>0z = z_{1 - \alpha/2} > 0 be the upper α/2\alpha/2 point of the standard normal law. The two-sided score test of H0:p=p0H_0: p = p_0 accepts when (x−np0)2≤z2np0(1−p0)(x - n p_0)^2 \le z^2 n p_0 (1 - p_0). The score of the binomial log-likelihood at p0p_0 is (x−np0)/(p0(1−p0))(x - n p_0)/(p_0(1 - p_0)) and the Fisher information is n/(p0(1−p0))n/(p_0(1 - p_0)), so this is the squared score statistic compared with z2z^2.

Claim 1 (the acceptance set is the interval of the page). For p∈[0,1]p \in [0, 1], the score test accepts pp if and only if L≤p≤UL \le p \le U, where

L,U=c∓h,c=x+z2/2n+z2,h=zn+z2x(n−x)n+z24.L, U = c \mp h, \qquad c = \frac{x + z^2/2}{n + z^2}, \qquad h = \frac{z}{n + z^2} \sqrt{\frac{x (n - x)}{n} + \frac{z^2}{4}}.

Proof. Expand the acceptance condition and divide by n>0n > 0:

q(p)=(n+z2)p2−(2x+z2)p+x2n≤0.q(p) = (n + z^2) p^2 - (2x + z^2) p + \frac{x^2}{n} \le 0.

qq is a quadratic with positive leading coefficient. Its discriminant is

(2x+z2)2−4(n+z2)x2n=4xz2+z4−4z2x2n=4z2(x(n−x)n+z24)>0,(2x + z^2)^2 - 4 (n + z^2) \frac{x^2}{n} = 4 x z^2 + z^4 - \frac{4 z^2 x^2}{n} = 4 z^2 \Big(\frac{x(n - x)}{n} + \frac{z^2}{4}\Big) > 0,

so qq has two real roots c∓hc \mp h, and q(p)≤0q(p) \le 0 exactly between them. □\square

Claim 2 (the ends lie in [0,1][0, 1] and contain x/nx/n). q(0)=x2/n≥0q(0) = x^2/n \ge 0 and q(1)=n−2x+x2/n=(n−x)2/n≥0q(1) = n - 2x + x^2/n = (n - x)^2/n \ge 0, and the vertex cc lies in (0,1)(0, 1). A convex quadratic that is non-negative at 00 and at 11, with its vertex between them, has both roots in [0,1][0, 1]. Also q(x/n)=−z2xn(1−xn)≤0q(x/n) = -z^2 \frac{x}{n}\big(1 - \frac{x}{n}\big) \le 0, so L≤x/n≤UL \le x/n \le U. The root 00 occurs exactly when x=0x = 0, and the root 11 exactly when x=nx = n. □\square

Claim 3 (the code computes these roots). Lines L2 and L3 compute cc and hh, and line L4 sets U=c+hU = c + h, or U=1U = 1 exactly when x=nx = n. By Vieta's formulas the product of the roots is (x2/n)/(n+z2)(x^2/n)/(n + z^2), so line L5 computes L=(x2/n)/((n+z2)U)L = (x^2/n)/((n + z^2) U). Since U≥c>0U \ge c > 0, the division is safe. This form has no subtraction, so it does not lose digits when cc and hh are close, and it gives L=0L = 0 exactly when x=0x = 0. □\square

Claim 4 (asymptotic coverage at a fixed pp). For fixed p∈(0,1)p \in (0, 1), the coverage Cn(p)=Pp(L≤p≤U)C_n(p) = P_p(L \le p \le U) tends to 1−α1 - \alpha as n→∞n \to \infty.

Proof. By Claim 1, Cn(p)=Pp(∣Zn∣≤z)C_n(p) = P_p(\lvert Z_n \rvert \le z) with Zn=(X−np)/np(1−p)Z_n = (X - np)/\sqrt{np(1 - p)}. By the central limit theorem, ZnZ_n converges in distribution to N(0,1)N(0, 1), and the normal law has no atom at ±z\pm z, so Cn(p)→1−αC_n(p) \to 1 - \alpha. □\square

The convergence is not uniform in pp. The next claim gives a bound that holds for every nn.

Claim 5 (a dip near the ends, for every nn). Let α≤0.38\alpha \le 0.38, and let λ∗\lambda^* be the smaller root of g(λ)=λ2−(2+z2)λ+1g(\lambda) = \lambda^2 - (2 + z^2)\lambda + 1. For every n≥1n \ge 1 and every pp with 0<p<λ∗/n0 < p < \lambda^*/n, the interval covers pp only when x=0x = 0, so Cn(p)=(1−p)nC_n(p) = (1 - p)^n. Hence

inf⁡0<p<1Cn(p)≤(1−λ∗n)n<e−λ∗.\inf_{0 < p < 1} C_n(p) \le \Big(1 - \frac{\lambda^*}{n}\Big)^n < e^{-\lambda^*}.

For α=0.05\alpha = 0.05, λ∗=0.176525\lambda^* = 0.176525 and e−λ∗=0.83818e^{-\lambda^*} = 0.83818.

Proof. Write s=z2s = z^2 and λ=np\lambda = np, so 0<λ<λ∗0 < \lambda < \lambda^*. Since g(0)=1>0g(0) = 1 > 0 and g(1)=−s<0g(1) = -s < 0, the smaller root satisfies 0<λ∗<10 < \lambda^* < 1, and g>0g > 0 on [0,λ∗)[0, \lambda^*). By Claim 1, the interval for xx covers pp if and only if (x−λ)2≤sλ(1−p)(x - \lambda)^2 \le s \lambda (1 - p).

  • x≥1x \ge 1 does not cover pp. Since λ<1\lambda < 1, (x−λ)2≥(1−λ)2(x - \lambda)^2 \ge (1 - \lambda)^2. Since g(λ)>0g(\lambda) > 0, (1−λ)2>sλ≥sλ(1−p)(1 - \lambda)^2 > s \lambda \ge s \lambda (1 - p).
  • x=0x = 0 covers pp. The condition is λ≤s(1−p)\lambda \le s(1 - p). Since p≤λp \le \lambda, it suffices that λ≤s(1−λ)\lambda \le s (1 - \lambda), that is λ≤s/(1+s)\lambda \le s/(1 + s). A direct expansion gives (1+s)2g(s/(1+s))=1−s2−s3(1 + s)^2 g\big(s/(1 + s)\big) = 1 - s^2 - s^3, which is at most 00 when s≥0.7549s \ge 0.7549, that is when z≥0.8688z \ge 0.8688, which holds for α≤0.38\alpha \le 0.38. Then s/(1+s)s/(1 + s) is not in the region where g>0g > 0, so λ<λ∗≤s/(1+s)\lambda < \lambda^* \le s/(1 + s).

So Cn(p)=Pp(X=0)=(1−p)nC_n(p) = P_p(X = 0) = (1 - p)^n. Letting pp rise to λ∗/n\lambda^*/n gives the first bound, and (1−t/n)n<e−t(1 - t/n)^n < e^{-t} for 0<t<n0 < t < n gives the second. □\square

What is proved and what is measured. Claims 1 to 5 are proved. The mean coverage near 1−α1 - \alpha, the place of the smallest coverage on a grid, and the share of pp with coverage below 1−α1 - \alpha are measured on the page by exact binomial sums over a grid of pp. 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 Θ(1)\Theta(1). □\square

Complexity

The interval costs a fixed number of arithmetic operations, one square root and one normal quantile: Θ(1)\Theta(1) time and space, independent of nn. Clopper-Pearson, by contrast, needs a root search over binomial tails or Beta quantiles.

Properties

  • Inside [0,1][0, 1]. Both ends lie in [0,1][0, 1] for every xx, with no truncation needed.
  • Never degenerate. The length is positive for every xx, including x=0x = 0 and x=nx = n.
  • Shrunk center. The center c=nn+z2p^+z2n+z2⋅12c = \frac{n}{n + z^2}\hat p + \frac{z^2}{n + z^2} \cdot \frac{1}{2} is a weighted mean of p^\hat p and 1/21/2. For 95% it is close to adding two successes and two failures.
  • Symmetry. L(x)=1−U(n−x)L(x) = 1 - U(n - x).
  • Monotone in xx. Both ends increase with xx.
  • 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 1−α1 - \alpha.

Variants and improvements

  • Continuity correction. Replace ∣x−np∣\lvert x - np \rvert by ∣x−np∣−1/2\lvert x - np \rvert - 1/2 in the inequality. The coverage rises toward that of Clopper-Pearson and the interval gets wider.
  • Agresti-Coull interval. Use n~=n+z2\tilde n = n + z^2 and p~=(x+z2/2)/n~\tilde p = (x + z^2/2)/\tilde n, the Wilson center, with the simple width zp~(1−p~)/n~z \sqrt{\tilde p (1 - \tilde p)/\tilde n}. 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 Beta(x+1/2,n−x+1/2)\text{Beta}(x + 1/2, n - x + 1/2) posterior, with the frequentist coverage studied by Brown, Cai and DasGupta. It is recommended with Wilson for small nn.
  • Modified ends. Brown, Cai and DasGupta (2001) suggest replacing the Wilson lower end for the smallest positive xx (up to 2 or 3, depending on nn) by a one-sided Poisson-based bound, which removes the deepest dips near p=0p = 0; the upper end changes in the same way by symmetry.
  • Wald interval. p^±zp^(1−p^)/n\hat p \pm z \sqrt{\hat p(1 - \hat p)/n} inverts the Wald test instead of the score test. Its coverage is erratic even for large nn, and it collapses to a point at x=0x = 0 and x=nx = n. 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 1−α1 - \alpha and a short interval matter more than a guarantee at every pp, and for any nn, including small nn. Use Clopper-Pearson when a guarantee at every pp is required. If pp 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 pp. At pp just below 0.1765/n0.1765/n the 95% interval covers pp with probability below 0.840.84, for every nn.
  • Uneven tails. Near p=0p = 0 almost all misses come from the interval lying above pp. Do not use one end of a two-sided Wilson interval as a one-sided bound at level 1−α/21 - \alpha/2 without checking.
  • The direct lower root. c−hc - h loses digits for small xx and can be slightly negative or nonzero at x=0x = 0. Use line L5.
  • Wrong variance. The score test uses the variance p0(1−p0)/np_0(1 - p_0)/n at the candidate p0p_0, not at p^\hat p. Using p^\hat p 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.

wilson_score_interval.pyI0RawGitHub
# 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 p^±zp^(1−p^)/n\hat p \pm z \sqrt{\hat p(1 - \hat p)/n} treats the estimate as if it were the true value in the variance, and solved ∣x−np∣=znp(1−p)\lvert x - np \rvert = z \sqrt{np(1 - p)} for pp 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 nn and recommended Wilson or Jeffreys for small nn.

References

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example