Algorithmcore
Clopper-Pearson interval
Also called exact binomial confidence interval.
A confidence interval for a binomial p that inverts two one-sided exact tests. Its endpoints are Beta quantiles, and its coverage is at least 1 - alpha for every p.
- Time
- Θ(n b) worstΘ(b) best
- Space
- Θ(1) extra
- Where
- b = the number of bisection steps (about 60 in double precision); n = the number of trials
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- C. J. Clopper, Egon S. Pearson, 1934
The Clopper-Pearson interval is a confidence interval for the success probability of a binomial distribution. From successes in trials, its lower end is the value of at which or more successes have probability , and its upper end is the value at which or fewer have probability . It is the set of that two one-sided exact binomial tests at level do not reject. Its coverage is at least for every and every , which is why it is often called "exact", but the coverage is usually well above , so the interval is conservative and wider than it needs to be on average.
In plain words
You saw 3 successes in 10 tries and want a range of plausible success rates. Try a candidate rate. If 3 or more successes would be very rare at that rate, the rate is too low. If 3 or fewer would be very rare, it is too high. "Very rare" means a chance of at most 2.5% on that side. The rates that pass both checks form the interval, here from about 0.067 to 0.652.
The interval never promises less than it says. Over many repeats, a 95% interval covers the true rate at least 95% of the time, whatever the true rate is. The price is that it often covers more than 95% of the time, so it is wider than the intervals that only promise 95% on average.
The problem
Input. A count from with fixed, and a level .
Output. An interval .
Coverage. Conservative: for every . The coverage is marginal over at a fixed ; nothing is conditioned on.
Construction. Inversion of a test, by test-interval duality. Write and . The ends solve
with and . The identity , where is the regularized incomplete beta function, turns these into Beta quantiles:
At the ends there are closed forms: and .
The algorithm
CLOPPER-PEARSON(x, n, α)- 1
if x = 0 then L ← 0 - 2
else L ← the root p in (0, 1) of P_p(X ≥ x) = α/2 ▷ bisection - 3
if x = n then U ← 1 - 4
else U ← the root p in (0, 1) of P_p(X ≤ x) = α/2 ▷ bisection - 5
return [L, U]
Each root is found by bisection on . The function is continuous and strictly increasing for , so a bracket that starts as always holds the root. The code halves the bracket until its midpoint equals one of its ends, which happens when the ends are adjacent floating point numbers. Each step sums one binomial tail in log space with lgamma, as in the binomial test. The lower tail is computed as the upper tail of the failures, so neither tail is found by subtraction from 1.
A library with a Beta quantile function can return the two Beta quantiles directly. The code of this page does not use one, since the standard library has none, but its tests check the identity with the incomplete beta function of the group helper.
Example
Take , and . Line L2 solves . The first steps of the bisection are:
| step | midpoint | the root is | |
|---|---|---|---|
| 1 | 0.5 | 0.94531 | below |
| 2 | 0.25 | 0.47441 | below |
| 3 | 0.125 | 0.11950 | below |
| 4 | 0.0625 | 0.02101 | above |
| 5 | 0.09375 | 0.05984 | below |
| 6 | 0.078125 | 0.03770 | below |
| 7 | 0.0703125 | 0.02867 | below |
| 8 | 0.06640625 | 0.02467 | above |
The bisection ends at . Line L4 gives , where . So the 95% interval is .
Other cases, at :
| , | Clopper-Pearson | Wilson | Wald |
|---|---|---|---|
| 3, 10 | [0.0667, 0.6525] | [0.1078, 0.6032] | [0.0160, 0.5840] |
| 0, 10 | [0, 0.3085] | [0, 0.2775] | [0, 0] |
| 10, 10 | [0.6915, 1] | [0.7225, 1] | [1, 1] |
| 7, 20 | [0.1539, 0.5922] | [0.1812, 0.5671] | [0.1410, 0.5590] |
For and , the closed form gives .
Exact coverage. The coverage at a fixed is , a finite sum, so it can be computed exactly with no simulation. On the grid at :
| Clopper-Pearson: minimum, mean | Wilson: minimum, mean, share of grid below 0.95 | Wald: minimum, mean | |
|---|---|---|---|
| 10 | 0.9611, 0.9838 | 0.8424, 0.9542, 44% | 0.0100, 0.7699 |
| 20 | 0.9581, 0.9770 | 0.8516, 0.9532, 40% | 0.0198, 0.8467 |
| 50 | 0.9527, 0.9693 | 0.8605, 0.9517, 40% | 0.0488, 0.9015 |
Clopper-Pearson never falls below 0.95, as the theorem says, and its mean coverage is near 0.98 for . The Wilson interval has mean coverage close to 0.95 but dips to about 0.85 near the ends of . The Wald interval collapses to a point at and and is the worst of the three.
Correctness
The full proof is in proofs/correctness.md. The derivative of in telescopes to , which proves the Beta identity and that each end is a unique root. Strict monotonicity gives exactly when . The set of such is an upper tail of , and an upper tail with at its smallest point has probability less than . The same holds for , and the two miss events are disjoint, so the coverage is greater than at every .
This is a proof for every , not a measurement. In contrast, the coverage of the Wilson interval is only measured, by the exact sums above.
Proof: The Clopper-Pearson interval is well defined and has coverage at least 1 - alpha for every pfull
Let with , and let . Write and . The interval of the page is with , , and otherwise
Lemma 1 (the tail is a Beta integral). For and ,
Proof. Both sides are at . Differentiate the sum term by term. Using and ,
with the convention . The sum telescopes to its first term, , which is the integrand.
Lemma 2 (the endpoints exist, are unique and are ordered). For , the map is continuous and strictly increasing on , from to , because its derivative in Lemma 1 is positive on . So exists, is unique and lies in . For , is continuous and strictly decreasing from to , so exists, is unique and lies in . Moreover:
- if and only if , and if and only if , by strict monotonicity.
- . At with , , so by the previous item. The cases and are clear.
- and are strictly increasing in , because is strictly decreasing in for fixed , and so is as a function of .
By Lemma 1, is the quantile of . By the same lemma applied to , is the quantile of .
Theorem (conservative coverage). For every , .
Proof. The interval misses when or . These events are disjoint, because . If then requires , which has probability , and is impossible; the case is symmetric. So let .
By Lemma 2, ; for , . The set is an upper set of the integers , because is decreasing in . If is empty, the event has probability . Otherwise let be its smallest element. Then .
In the same way, is a lower set with largest element when it is not empty, and its probability is .
So the probability of a miss is less than , and the coverage is greater than .
The inequality is strict for each in , but the infimum of the coverage over can approach for large . The coverage is not continuous in : it jumps at each endpoint and .
Duality. By Lemma 2, if and only if and , that is, if and only if neither one-sided exact binomial test rejects at level . This is the doubling rule of the two-sided test, and the theorem above is the general test-interval duality for it.
The algorithm. Lines L1 and L3 set the fixed endpoints. Lines L2 and L4 find the unique roots of Lemma 2 by bisection on . Bisection keeps a bracket with $f(lo) < $ target for the increasing function , so the root stays in the bracket, and the loop stops when the midpoint equals an end of the bracket, that is, when the bracket is two adjacent floating point numbers. Each step evaluates one binomial tail of at most terms.
Complexity
Each tail evaluation costs operations in the worst case, with lgamma and exp as unit operations, and the bisection does steps, about 55 to 70 in double precision, more when an end is very close to 0. So the time is and the extra space is . More exactly, the upper tail for has terms and the tail of the failures for has terms. For or one end is free and the other tail has one term, so the time is . With a Beta quantile routine based on a continued fraction for , the cost per evaluation no longer grows linearly in , and Newton steps can replace most bisection steps.
Properties
- Conservative. The coverage is above at every , and much higher for small . The interval is wider than intervals with coverage near on average.
- Equal tails. Each side misses with probability less than . One-sided bounds are the same construction with in place of .
- Symmetry. , because the roles of successes and failures swap.
- Monotone in . Both ends increase strictly with .
- Never degenerate. The interval has positive length for every , including and , unlike the Wald interval.
- Not the shortest. Among intervals with guaranteed coverage, others are shorter on average; see the variants.
Variants and improvements
- One-sided bound and the rule of three. With , the one-sided upper bound at level is , about for .
- Mid-p interval. Replace by and similarly on the other side. The coverage is close to on average, but it is no longer guaranteed.
- Shorter intervals with the same guarantee. Inverting other exact tests gives intervals that are contained in Clopper-Pearson for many : the Sterne interval inverts the minimum-likelihood two-sided test, and Blaker (2000) inverts a test that keeps the result an interval and nested in . Sterne's set can have gaps; see the binomial test.
- Approximate intervals. The Wilson score interval, the Agresti-Coull interval and the Jeffreys interval (the equal-tailed interval of the posterior) have mean coverage near and are shorter. Brown, Cai and DasGupta (2001) recommend Wilson or Jeffreys for small .
- A Bayesian view. and are quantiles of the posteriors under the improper priors and . This is a coincidence of formulas; the coverage statement is frequentist and is not a credible interval statement.
When to use it
Use it when a guarantee at every is required, for example in regulation, quality control or safety work, where a reported upper bound on a failure rate must hold. It is also the standard report for or . When the goal is accurate average coverage and shorter intervals, use Wilson or Jeffreys instead. Do not use the Wald interval for small or for near 0 or 1.
Pitfalls
- "Exact" does not mean coverage equal to . It means the coverage is computed from the exact binomial law and is at least . The coverage is above almost everywhere.
- Swapping the Beta parameters. The lower end uses and the upper end uses . Using for both gives the posterior of a uniform prior, not this interval.
- Undefined quantiles at the ends. does not exist, so code must set and directly, as lines L1 and L3 do.
- Using for a small tail. For large , compute each tail as a direct sum or with the incomplete beta function, not as 1 minus the other tail.
- Dependence or overdispersion. The coverage proof needs . Clustered data give more spread and lower coverage.
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/clopper-pearson-interval/. The authors are listed in prov/X4CPDK.jsonl.
import math
def binomial_upper_tail(x: int, n: int, p: float) -> float:
"""P_p(X >= x) for X ~ Binomial(n, p), summed directly in log space."""
if x <= 0:
return 1.0
if x > n:
return 0.0
if p <= 0.0:
return 0.0
if p >= 1.0:
return 1.0
log_p, log_q, log_n_fact = math.log(p), math.log1p(-p), math.lgamma(n + 1)
return math.fsum(
math.exp(log_n_fact - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * log_p + (n - k) * log_q)
for k in range(x, n + 1)
)
def binomial_lower_tail(x: int, n: int, p: float) -> float:
"""P_p(X <= x), from the upper tail of the failures: X <= x iff n - X >= n - x."""
return binomial_upper_tail(n - x, n, 1.0 - p)
def _solve_increasing(f, target: float) -> float:
"""The root in [0, 1] of f(p) = target for a continuous increasing f, by bisection."""
lo, hi = 0.0, 1.0
while True:
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
return mid
if f(mid) < target:
lo = mid
else:
hi = mid
def clopper_pearson_interval(x: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
"""The Clopper-Pearson interval [L, U] for a binomial p at level 1 - alpha.
L solves P_L(X >= x) = alpha/2 (L = 0 when x = 0), and U solves
P_U(X <= x) = alpha/2 (U = 1 when x = n). Equivalently, L is the alpha/2
quantile of Beta(x, n - x + 1) and U is the 1 - alpha/2 quantile of
Beta(x + 1, n - x). Each endpoint is found by bisection to the last bit.
"""
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)")
if x == 0: # @line L1
lower = 0.0
else: # @line L2
lower = _solve_increasing(lambda p: binomial_upper_tail(x, n, p), alpha / 2)
if x == n: # @line L3
upper = 1.0
else: # @line L4
upper = _solve_increasing(lambda p: -binomial_lower_tail(x, n, p), -alpha / 2)
return lower, upper # @line L5
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_clopper_pearson_interval.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/clopper-pearson-interval/. The authors are listed in prov/X4CPDK.jsonl.
import math
from fractions import Fraction
import pytest
from clopper_pearson_interval import clopper_pearson_interval
from stdist import beta_inc
def exact_pmf(n: int, p: Fraction) -> list[Fraction]:
return [math.comb(n, k) * p**k * (1 - p) ** (n - k) for k in range(n + 1)]
def test_page_examples() -> None:
assert clopper_pearson_interval(3, 10) == pytest.approx((0.066739511, 0.652452850), abs=1e-8)
assert clopper_pearson_interval(7, 20) == pytest.approx((0.153909, 0.592189), abs=1e-6)
lo, hi = clopper_pearson_interval(0, 10)
assert lo == 0.0 and hi == pytest.approx(1 - 0.025**0.1, abs=1e-14)
lo, hi = clopper_pearson_interval(10, 10)
assert hi == 1.0 and lo == pytest.approx(0.025**0.1, abs=1e-14)
def test_closed_forms_at_the_ends() -> None:
# x = 0: P_U(X <= 0) = (1 - U)^n = alpha/2. x = n: L^n = alpha/2.
for n in range(1, 60):
for alpha in (0.01, 0.05, 0.1, 0.32):
assert clopper_pearson_interval(0, n, alpha)[1] == pytest.approx(1 - (alpha / 2) ** (1 / n), abs=1e-13)
assert clopper_pearson_interval(n, n, alpha)[0] == pytest.approx((alpha / 2) ** (1 / n), abs=1e-13)
def test_endpoints_solve_the_tail_equations_exactly() -> None:
# Check with exact Fraction tails that each endpoint brackets alpha/2.
alpha = Fraction(1, 20)
for n in (1, 2, 5, 9, 16):
for x in range(n + 1):
lo, hi = clopper_pearson_interval(x, n, 0.05)
eps = Fraction(1, 10**9)
if x > 0:
below = sum(exact_pmf(n, Fraction(lo) - eps)[x:])
above = sum(exact_pmf(n, Fraction(lo) + eps)[x:])
assert below < alpha / 2 < above
if x < n:
below = sum(exact_pmf(n, Fraction(hi) - eps)[: x + 1])
above = sum(exact_pmf(n, Fraction(hi) + eps)[: x + 1])
assert below > alpha / 2 > above
def test_beta_quantile_identity() -> None:
# L is the alpha/2 quantile of Beta(x, n - x + 1); U is the 1 - alpha/2 quantile of Beta(x + 1, n - x).
for n in (3, 10, 25, 80):
for x in range(n + 1):
lo, hi = clopper_pearson_interval(x, n, 0.05)
if x > 0:
assert beta_inc(x, n - x + 1, lo) == pytest.approx(0.025, abs=1e-10)
if x < n:
assert beta_inc(x + 1, n - x, hi) == pytest.approx(0.975, abs=1e-10)
def test_exact_coverage_is_at_least_nominal() -> None:
# Exact coverage by summing binomial probabilities, on a grid of p.
for n in (5, 10, 20, 30):
intervals = [clopper_pearson_interval(x, n, 0.05) for x in range(n + 1)]
bounds = [(Fraction(a), Fraction(b)) for a, b in intervals]
for k in range(1, 200):
p = Fraction(k, 200)
w = exact_pmf(n, p)
cover = sum(w[x] for x in range(n + 1) if bounds[x][0] <= p <= bounds[x][1])
assert cover >= Fraction(95, 100), (n, p, float(cover))
def test_inverts_the_doubled_binomial_test() -> None:
# p0 is inside [L, U] exactly when neither one-sided exact test rejects at alpha/2.
alpha = Fraction(1, 20)
for n in (4, 11, 18):
for x in range(n + 1):
lo, hi = clopper_pearson_interval(x, n, 0.05)
for k in range(1, 400):
p0 = Fraction(k, 400)
w = exact_pmf(n, p0)
accept = sum(w[x:]) > alpha / 2 and sum(w[: x + 1]) > alpha / 2
assert accept == (lo < p0 < hi), (n, x, p0)
def test_symmetry_and_monotonicity() -> None:
n = 40
rows = [clopper_pearson_interval(x, n, 0.1) for x in range(n + 1)]
for x in range(n + 1):
assert rows[x][0] == pytest.approx(1 - rows[n - x][1], abs=1e-13)
assert all(a[0] < b[0] and a[1] < b[1] for a, b in zip(rows, rows[1:]))
def test_large_n_and_errors() -> None:
lo, hi = clopper_pearson_interval(500, 1000)
assert 0.46 < lo < 0.47 and 0.53 < hi < 0.54
assert lo == pytest.approx(1 - hi, abs=1e-12)
for bad in ((3, 2), (-1, 5), (1, 0)):
with pytest.raises(ValueError):
clopper_pearson_interval(*bad)
with pytest.raises(ValueError):
clopper_pearson_interval(1, 5, 1.5)
History
Clopper and Pearson (1934) gave the interval and charts of its ends for several , as one of the first applications of Neyman's theory of confidence intervals, and called the ends confidence or fiducial limits. The Beta form of the ends follows from the identity between binomial tails and the incomplete beta function. Interest returned after Agresti and Coull (1998) and Brown, Cai and DasGupta (2001) showed by exact coverage computations how conservative Clopper-Pearson is and how badly the textbook Wald interval behaves, and both papers recommended approximate intervals for routine use.
References
- C. J. Clopper and E. S. Pearson, The use of confidence or fiducial limits illustrated in the case of the binomial, Biometrika 26(4), 1934, pp. 404 to 413
- 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 exact coverage of the Wald, Wilson, Agresti-Coull, Jeffreys and Clopper-Pearson 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
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Section 1.4 (inference for binomial parameters) and Chapter 16 (small-sample exact inference and its conservatism)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 9.2 (methods of finding interval estimators, inverting a test and pivoting the CDF for discrete families)
Where this leads
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 X4CPDK Edit this page History Report an error Markdown