Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
Origin
C. J. Clopper, Egon S. Pearson, 1934

The Clopper-Pearson interval is a confidence interval for the success probability pp of a binomial distribution. From xx successes in nn trials, its lower end LL is the value of pp at which xx or more successes have probability α/2\alpha/2, and its upper end UU is the value at which xx or fewer have probability α/2\alpha/2. It is the set of p0p_0 that two one-sided exact binomial tests at level α/2\alpha/2 do not reject. Its coverage is at least 1−α1 - \alpha for every pp and every nn, which is why it is often called "exact", but the coverage is usually well above 1−α1 - \alpha, 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 x∈{0,…,n}x \in \{0, \ldots, n\} from X∼Binomial(n,p)X \sim \text{Binomial}(n, p) with n≥1n \ge 1 fixed, and a level α∈(0,1)\alpha \in (0, 1).

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

Coverage. Conservative: Pp(L(X)≤p≤U(X))≥1−αP_p(L(X) \le p \le U(X)) \ge 1 - \alpha for every p∈[0,1]p \in [0, 1]. The coverage is marginal over XX at a fixed pp; nothing is conditioned on.

Construction. Inversion of a test, by test-interval duality. Write Gp(x)=Pp(X≥x)G_p(x) = P_p(X \ge x) and Fp(x)=Pp(X≤x)F_p(x) = P_p(X \le x). The ends solve

GL(x)=α2    (x≥1),FU(x)=α2    (x≤n−1),G_{L}(x) = \frac{\alpha}{2} \;\; (x \ge 1), \qquad F_{U}(x) = \frac{\alpha}{2} \;\; (x \le n - 1),

with L(0)=0L(0) = 0 and U(n)=1U(n) = 1. The identity Gp(x)=Ip(x,n−x+1)G_p(x) = I_p(x, n - x + 1), where II is the regularized incomplete beta function, turns these into Beta quantiles:

L(x)=B−1(α2; x, n−x+1),U(x)=B−1(1−α2; x+1, n−x).L(x) = B^{-1}\big(\tfrac{\alpha}{2};\, x,\, n - x + 1\big), \qquad U(x) = B^{-1}\big(1 - \tfrac{\alpha}{2};\, x + 1,\, n - x\big).

At the ends there are closed forms: U(0)=1−(α/2)1/nU(0) = 1 - (\alpha/2)^{1/n} and L(n)=(α/2)1/nL(n) = (\alpha/2)^{1/n}.

The algorithm

  1. CLOPPER-PEARSON(x, n, α)
  2. 1if x = 0 then L ← 0
  3. 2else L ← the root p in (0, 1) of P_p(X ≥ x) = α/2 ▷ bisection
  4. 3if x = n then U ← 1
  5. 4else U ← the root p in (0, 1) of P_p(X ≤ x) = α/2 ▷ bisection
  6. 5return [L, U]

Each root is found by bisection on [0,1][0, 1]. The function p↦Pp(X≥x)p \mapsto P_p(X \ge x) is continuous and strictly increasing for x≥1x \ge 1, so a bracket that starts as [0,1][0, 1] 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 Pp(X≤x)P_p(X \le x) is computed as the upper tail P1−p(n−X≥n−x)P_{1-p}(n - X \ge n - x) 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 n=10n = 10, x=3x = 3 and α=0.05\alpha = 0.05. Line L2 solves Pp(X≥3)=0.025P_p(X \ge 3) = 0.025. The first steps of the bisection are:

step midpoint pp Pp(X≥3)P_p(X \ge 3) 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 L=0.0667395L = 0.0667395. Line L4 gives U=0.6524529U = 0.6524529, where PU(X≤3)=0.025P_U(X \le 3) = 0.025. So the 95% interval is [0.0667,0.6525][0.0667, 0.6525].

Other cases, at α=0.05\alpha = 0.05:

xx, nn Clopper-Pearson Wilson Wald p^±zp^(1−p^)/n\hat p \pm z \sqrt{\hat p(1 - \hat p)/n}
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 x=0x = 0 and n=10n = 10, the closed form gives U=1−0.0251/10=0.3085U = 1 - 0.025^{1/10} = 0.3085.

Exact coverage. The coverage at a fixed pp is 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}, a finite sum, so it can be computed exactly with no simulation. On the grid p=0.001,0.002,…,0.999p = 0.001, 0.002, \ldots, 0.999 at α=0.05\alpha = 0.05:

nn 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 n=10n = 10. The Wilson interval has mean coverage close to 0.95 but dips to about 0.85 near the ends of [0,1][0, 1]. The Wald interval collapses to a point at x=0x = 0 and x=nx = n and is the worst of the three.

Correctness

The full proof is in proofs/correctness.md. The derivative of Gp(x)G_p(x) in pp telescopes to n(n−1x−1)px−1(1−p)n−x>0n \binom{n-1}{x-1} p^{x-1}(1-p)^{n-x} > 0, which proves the Beta identity and that each end is a unique root. Strict monotonicity gives L(x)>pL(x) > p exactly when Gp(x)<α/2G_p(x) < \alpha/2. The set of such xx is an upper tail of {0,…,n}\{0, \ldots, n\}, and an upper tail with Gp<α/2G_p < \alpha/2 at its smallest point has probability less than α/2\alpha/2. The same holds for U(x)<pU(x) < p, and the two miss events are disjoint, so the coverage is greater than 1−α1 - \alpha at every pp.

This is a proof for every nn, 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 X∼Binomial(n,p)X \sim \text{Binomial}(n, p) with n≥1n \ge 1, and let 0<α<10 < \alpha < 1. Write Gp(x)=Pp(X≥x)G_p(x) = P_p(X \ge x) and Fp(x)=Pp(X≤x)F_p(x) = P_p(X \le x). The interval of the page is [L(x),U(x)][L(x), U(x)] with L(0)=0L(0) = 0, U(n)=1U(n) = 1, and otherwise

GL(x)(x)=α/2(1≤x≤n),FU(x)(x)=α/2(0≤x≤n−1).G_{L(x)}(x) = \alpha/2 \quad (1 \le x \le n), \qquad F_{U(x)}(x) = \alpha/2 \quad (0 \le x \le n - 1).

Lemma 1 (the tail is a Beta integral). For 1≤x≤n1 \le x \le n and 0≤p≤10 \le p \le 1,

Gp(x)=n!(x−1)! (n−x)!∫0ptx−1(1−t)n−x dt=Ip(x,n−x+1).G_p(x) = \frac{n!}{(x-1)!\,(n-x)!} \int_0^p t^{x-1} (1 - t)^{n-x} \, dt = I_p(x, n - x + 1).

Proof. Both sides are 00 at p=0p = 0. Differentiate the sum Gp(x)=∑k=xn(nk)pk(1−p)n−kG_p(x) = \sum_{k=x}^{n} \binom{n}{k} p^k (1-p)^{n-k} term by term. Using k(nk)=n(n−1k−1)k \binom{n}{k} = n \binom{n-1}{k-1} and (n−k)(nk)=n(n−1k)(n - k)\binom{n}{k} = n \binom{n-1}{k},

ddpGp(x)=n∑k=xn[(n−1k−1)pk−1(1−p)n−k−(n−1k)pk(1−p)n−k−1],\frac{d}{dp} G_p(x) = n \sum_{k=x}^{n} \Big[\tbinom{n-1}{k-1} p^{k-1}(1-p)^{n-k} - \tbinom{n-1}{k} p^{k}(1-p)^{n-k-1}\Big],

with the convention (n−1n)=0\binom{n-1}{n} = 0. The sum telescopes to its first term, n(n−1x−1)px−1(1−p)n−xn \binom{n-1}{x-1} p^{x-1} (1-p)^{n-x}, which is the integrand. □\square

Lemma 2 (the endpoints exist, are unique and are ordered). For 1≤x≤n1 \le x \le n, the map p↦Gp(x)p \mapsto G_p(x) is continuous and strictly increasing on [0,1][0, 1], from 00 to 11, because its derivative in Lemma 1 is positive on (0,1)(0, 1). So L(x)L(x) exists, is unique and lies in (0,1)(0, 1). For 0≤x≤n−10 \le x \le n - 1, Fp(x)=1−Gp(x+1)F_p(x) = 1 - G_p(x + 1) is continuous and strictly decreasing from 11 to 00, so U(x)U(x) exists, is unique and lies in (0,1)(0, 1). Moreover:

  • p<L(x)p < L(x) if and only if Gp(x)<α/2G_p(x) < \alpha/2, and p>U(x)p > U(x) if and only if Fp(x)<α/2F_p(x) < \alpha/2, by strict monotonicity.
  • L(x)<U(x)L(x) < U(x). At p=L(x)p = L(x) with x<nx < n, Fp(x)=1−Gp(x)+Pp(X=x)>1−α/2>α/2F_p(x) = 1 - G_p(x) + P_p(X = x) > 1 - \alpha/2 > \alpha/2, so L(x)<U(x)L(x) < U(x) by the previous item. The cases x=0x = 0 and x=nx = n are clear.
  • LL and UU are strictly increasing in xx, because Gp(x)G_p(x) is strictly decreasing in xx for fixed p∈(0,1)p \in (0, 1), and so is Fp(x)F_p(x) as a function of −x-x.

By Lemma 1, L(x)L(x) is the α/2\alpha/2 quantile of Beta(x,n−x+1)\text{Beta}(x, n - x + 1). By the same lemma applied to Gp(x+1)G_p(x + 1), U(x)U(x) is the 1−α/21 - \alpha/2 quantile of Beta(x+1,n−x)\text{Beta}(x + 1, n - x). □\square

Theorem (conservative coverage). For every p∈[0,1]p \in [0, 1], Pp(L(X)≤p≤U(X))≥1−αP_p\big(L(X) \le p \le U(X)\big) \ge 1 - \alpha.

Proof. The interval misses pp when L(X)>pL(X) > p or U(X)<pU(X) < p. These events are disjoint, because L(X)<U(X)L(X) < U(X). If p=0p = 0 then L(X)>0L(X) > 0 requires X≥1X \ge 1, which has probability 00, and U(X)<0U(X) < 0 is impossible; the case p=1p = 1 is symmetric. So let 0<p<10 < p < 1.

By Lemma 2, {x:L(x)>p}={x≥1:Gp(x)<α/2}\{x : L(x) > p\} = \{x \ge 1 : G_p(x) < \alpha/2\}; for x=0x = 0, L(0)=0≤pL(0) = 0 \le p. The set A={x:Gp(x)<α/2}A = \{x : G_p(x) < \alpha/2\} is an upper set of the integers 0,…,n0, \ldots, n, because Gp(x)G_p(x) is decreasing in xx. If AA is empty, the event has probability 00. Otherwise let x∗x^* be its smallest element. Then Pp(X∈A)=Pp(X≥x∗)=Gp(x∗)<α/2P_p(X \in A) = P_p(X \ge x^*) = G_p(x^*) < \alpha/2.

In the same way, {x:U(x)<p}={x≤n−1:Fp(x)<α/2}\{x : U(x) < p\} = \{x \le n - 1 : F_p(x) < \alpha/2\} is a lower set with largest element x∗∗x^{**} when it is not empty, and its probability is Fp(x∗∗)<α/2F_p(x^{**}) < \alpha/2.

So the probability of a miss is less than α/2+α/2=α\alpha/2 + \alpha/2 = \alpha, and the coverage is greater than 1−α1 - \alpha. □\square

The inequality is strict for each pp in (0,1)(0, 1), but the infimum of the coverage over pp can approach 1−α1 - \alpha for large nn. The coverage is not continuous in pp: it jumps at each endpoint L(x)L(x) and U(x)U(x).

Duality. By Lemma 2, p0∈(L(x),U(x))p_0 \in (L(x), U(x)) if and only if Gp0(x)>α/2G_{p_0}(x) > \alpha/2 and Fp0(x)>α/2F_{p_0}(x) > \alpha/2, that is, if and only if neither one-sided exact binomial test rejects at level α/2\alpha/2. 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 [0,1][0, 1]. Bisection keeps a bracket [lo,hi][lo, hi] with $f(lo) < $ target ≤f(hi)\le f(hi) for the increasing function ff, 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 n+1n + 1 terms. □\square

Complexity

Each tail evaluation costs Θ(n)\Theta(n) operations in the worst case, with lgamma and exp as unit operations, and the bisection does bb steps, about 55 to 70 in double precision, more when an end is very close to 0. So the time is Θ(nb)\Theta(n b) and the extra space is Θ(1)\Theta(1). More exactly, the upper tail for LL has n−x+1n - x + 1 terms and the tail of the failures for UU has x+1x + 1 terms. For x=0x = 0 or x=nx = n one end is free and the other tail has one term, so the time is Θ(b)\Theta(b). With a Beta quantile routine based on a continued fraction for IpI_p, the cost per evaluation no longer grows linearly in nn, and Newton steps can replace most bisection steps.

Properties

  • Conservative. The coverage is above 1−α1 - \alpha at every pp, and much higher for small nn. The interval is wider than intervals with coverage near 1−α1 - \alpha on average.
  • Equal tails. Each side misses with probability less than α/2\alpha/2. One-sided bounds are the same construction with α\alpha in place of α/2\alpha/2.
  • Symmetry. L(x)=1−U(n−x)L(x) = 1 - U(n - x), because the roles of successes and failures swap.
  • Monotone in xx. Both ends increase strictly with xx.
  • Never degenerate. The interval has positive length for every xx, including x=0x = 0 and x=nx = n, 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 x=0x = 0, the one-sided upper bound at level 1−α1 - \alpha is 1−α1/n1 - \alpha^{1/n}, about 3/n3/n for α=0.05\alpha = 0.05.
  • Mid-p interval. Replace Pp(X≥x)P_p(X \ge x) by Pp(X>x)+12Pp(X=x)P_p(X > x) + \frac{1}{2} P_p(X = x) and similarly on the other side. The coverage is close to 1−α1 - \alpha 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 xx: 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 α\alpha. 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 Beta(x+1/2,n−x+1/2)\text{Beta}(x + 1/2, n - x + 1/2) posterior) have mean coverage near 1−α1 - \alpha and are shorter. Brown, Cai and DasGupta (2001) recommend Wilson or Jeffreys for small nn.
  • A Bayesian view. L(x)L(x) and U(x)U(x) are quantiles of the posteriors under the improper priors Beta(0,1)\text{Beta}(0, 1) and Beta(1,0)\text{Beta}(1, 0). 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 pp 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 x=0x = 0 or x=nx = n. When the goal is accurate average coverage and shorter intervals, use Wilson or Jeffreys instead. Do not use the Wald interval for small nn or for pp near 0 or 1.

Pitfalls

  • "Exact" does not mean coverage equal to 1−α1 - \alpha. It means the coverage is computed from the exact binomial law and is at least 1−α1 - \alpha. The coverage is above 1−α1 - \alpha almost everywhere.
  • Swapping the Beta parameters. The lower end uses Beta(x,n−x+1)\text{Beta}(x, n - x + 1) and the upper end uses Beta(x+1,n−x)\text{Beta}(x + 1, n - x). Using Beta(x+1,n−x+1)\text{Beta}(x + 1, n - x + 1) for both gives the posterior of a uniform prior, not this interval.
  • Undefined quantiles at the ends. Beta(0,⋅)\text{Beta}(0, \cdot) does not exist, so code must set L(0)=0L(0) = 0 and U(n)=1U(n) = 1 directly, as lines L1 and L3 do.
  • Using 1−F1 - F for a small tail. For large nn, 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 X∼Binomial(n,p)X \sim \text{Binomial}(n, p). 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.

clopper_pearson_interval.pyI0RawGitHub
# 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 nn, 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

  1. 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
  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 exact coverage of the Wald, Wilson, Agresti-Coull, Jeffreys and Clopper-Pearson 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
  4. 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)
  5. 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.

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