Algorithm Search⌘K

Algorithmintro

Binomial test

Also called exact binomial test.

Tests H_0 p = p_0 from x successes in n independent trials with the exact Binomial(n, p_0) law. Valid for every n; size at most alpha; O(n) time.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the number of trials
Properties
deterministicexactofflineiterative
Origin
John Arbuthnot, H. O. Lancaster, 1710

The binomial test checks a hypothesis about the success probability pp of independent trials. It uses the count XX of successes in nn trials and the exact null law Binomial(n,p0)\text{Binomial}(n, p_0) of XX, so it needs no normal approximation and is valid for every nn. The one-sided p-value is a binomial tail. The two-sided p-value has two common definitions, which can give different answers; this page and its code use the sum of the probabilities of all outcomes that are at most as likely as the observed one, and offer doubling of the smaller tail as an option.

In plain words

You flip a coin 10 times and see 8 heads. Is the coin fair? If it is fair, you can list the chance of each possible number of heads, from 0 to 10. Then you add up the chances of the results that are as surprising as 8 heads, or more surprising. That sum is the p-value. Here it is about 0.11, so 8 heads in 10 flips is not strong evidence against a fair coin.

Nothing is approximated. The chances come straight from counting. Because the count can only take whole values, the test cannot hit a chosen error rate such as 5% exactly. It always stays at or below it.

The problem

Model. X1,…,XnX_1, \ldots, X_n are independent Bernoulli(p)(p) trials, and X=∑iXiX = \sum_i X_i is the number of successes, so X∼Binomial(n,p)X \sim \text{Binomial}(n, p) with the binomial distribution. The number of trials nn is fixed before the data are seen.

Hypotheses. H0:p=p0H_0 : p = p_0 against one of H1:p>p0H_1 : p > p_0 (one-sided, "greater"), H1:p<p0H_1 : p < p_0 (one-sided, "less") or H1:p≠p0H_1 : p \ne p_0 (two-sided).

Statistic. The observed count xx. Write b(k)=(nk)p0k(1−p0)n−kb(k) = \binom{n}{k} p_0^k (1 - p_0)^{n-k} for the null probability of kk successes.

Null distribution. Exact: X∼Binomial(n,p0)X \sim \text{Binomial}(n, p_0) under H0H_0, for every nn.

P-values.

  • Greater: Phi(x)=∑k≥xb(k)=Pp0(X≥x)P_{hi}(x) = \sum_{k \ge x} b(k) = P_{p_0}(X \ge x).
  • Less: Plo(x)=∑k≤xb(k)=Pp0(X≤x)P_{lo}(x) = \sum_{k \le x} b(k) = P_{p_0}(X \le x).
  • Two-sided, the minimum-likelihood rule: pml(x)=∑k:b(k)≤b(x)b(k)p_{ml}(x) = \sum_{k : b(k) \le b(x)} b(k). The outcomes "at least as extreme" are those that are at most as likely under H0H_0.
  • Two-sided, the doubling rule: pd(x)=min⁡{1,2min⁡(Plo(x),Phi(x))}p_d(x) = \min\{1, 2 \min(P_{lo}(x), P_{hi}(x))\}.

The two rules agree when p0=1/2p_0 = 1/2, where the law is symmetric. For other p0p_0 they differ, and neither one is always the smaller (see the example).

Rejection rule. Reject H0H_0 at level α\alpha when p(x)≤αp(x) \le \alpha. The size is at most α\alpha for every nn and p0p_0 (proved in Correctness). It equals α\alpha only when α\alpha happens to be one of the finitely many attainable tail sums, so the test is conservative.

The algorithm

  1. BINOMIAL-TEST(x, n, p0, alternative)
  2. 1w[k] ← C(n, k) p0^k (1 - p0)^(n - k) for k = 0 .. n ▷ in log space with lgamma
  3. 2P_hi ← w[x] + w[x + 1] + ... + w[n]
  4. 3P_lo ← w[0] + w[1] + ... + w[x]
  5. 4if alternative = greater then return P_hi
  6. 5if alternative = less then return P_lo
  7. 6t ← w[x] · (1 + δ) ▷ δ = 10^-7 absorbs rounding in ties
  8. 7P ← sum of w[k] over all k with w[k] ≤ t
  9. 8return min(1, P)

Line L1 computes log⁡b(k)=lgamma⁡(n+1)−lgamma⁡(k+1)−lgamma⁡(n−k+1)+klog⁡p0+(n−k)log⁡(1−p0)\log b(k) = \operatorname{lgamma}(n + 1) - \operatorname{lgamma}(k + 1) - \operatorname{lgamma}(n - k + 1) + k \log p_0 + (n - k) \log(1 - p_0) and then takes exp⁡\exp. This avoids the overflow of (nk)\binom{n}{k} and the underflow of p0kp_0^k for large nn; see binomial coefficient computation for the exact integer route. The cases p0=0p_0 = 0 and p0=1p_0 = 1 are point masses and are handled apart. Lines L2 and L3 sum each tail directly. The code uses math.fsum for the sums. The doubling rule replaces lines L6 to L8 by min⁡(1,2min⁡(Plo,Phi))\min(1, 2 \min(P_{lo}, P_{hi})).

Example

A fair coin. n=10n = 10, x=8x = 8, p0=1/2p_0 = 1/2. The null probabilities are (10k)/1024\binom{10}{k}/1024: 1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1, each over 1024. The one-sided p-value is Phi(8)=(45+10+1)/1024=7/128=0.0547P_{hi}(8) = (45 + 10 + 1)/1024 = 7/128 = 0.0547. Line L6 sets t=45/1024t = 45/1024, and the outcomes with b(k)≤tb(k) \le t are k=0,1,2,8,9,10k = 0, 1, 2, 8, 9, 10. So pml(8)=112/1024=7/64=0.1094p_{ml}(8) = 112/1024 = 7/64 = 0.1094, which is also 2Phi(8)2 P_{hi}(8).

An asymmetric null. n=10n = 10, p0=0.2p_0 = 0.2. The null probabilities are:

kk 0 1 2 3 4 5 6 7 8 9 10
b(k)b(k) 0.10737 0.26844 0.30199 0.20133 0.08808 0.02642 0.00551 0.00079 0.00007 0.000004 0.0000001
  • x=5x = 5: Phi(5)=0.0327934976P_{hi}(5) = 0.0327934976. No outcome below the mode has a probability as small as b(5)=0.0264b(5) = 0.0264, so pml(5)=0.0328p_{ml}(5) = 0.0328, while pd(5)=0.0656p_d(5) = 0.0656. At α=0.05\alpha = 0.05 the minimum-likelihood rule rejects and the doubling rule does not.
  • x=0x = 0: Plo(0)=0.810=0.1073741824P_{lo}(0) = 0.8^{10} = 0.1073741824 and pd(0)=0.2147483648p_d(0) = 0.2147483648. The outcomes with b(k)≤b(0)b(k) \le b(0) are k=0k = 0 and k=4,…,10k = 4, \ldots, 10, so pml(0)=0.228248064p_{ml}(0) = 0.228248064. Here the minimum-likelihood rule gives the larger value.

Attained size. For n=10n = 10, p0=1/2p_0 = 1/2, the one-sided test at α=0.05\alpha = 0.05 rejects for x∈{9,10}x \in \{9, 10\}, because Phi(8)=0.0547>0.05P_{hi}(8) = 0.0547 > 0.05. Its size is 11/1024=0.010711/1024 = 0.0107, far below 0.050.05. The two-sided test rejects for x∈{0,1,9,10}x \in \{0, 1, 9, 10\}, with size 22/1024=0.021522/1024 = 0.0215.

A small tail. For n=1000n = 1000, x=700x = 700, p0=1/2p_0 = 1/2, the exact upper tail is 8.83×10−388.83 \times 10^{-38}. Line L2 returns this to 9 digits. Computing it as 1−Plo(699)1 - P_{lo}(699) in double precision returned 2.2×10−132.2 \times 10^{-13}, which is wrong by 24 orders of magnitude.

All the numbers above come from exact Fraction sums, and the tests check the code against them.

Correctness

The full proof is in proofs/correctness.md. Lines L1 to L8 return the tail sums of the definitions. Validity rests on one lemma: if p(x)=P(T(X)≥T(x))p(x) = P(T(X) \ge T(x)) for some ordering TT of the finite sample space, then P(p(X)≤u)≤uP(p(X) \le u) \le u for every uu. The set {x:p(x)≤u}\{x : p(x) \le u\} is contained in the tail {T≥T(x∗)}\{T \ge T(x^*)\} of its own smallest member x∗x^*, and that tail has probability p(x∗)≤up(x^*) \le u. The one-sided p-values use T(x)=±xT(x) = \pm x, and the minimum-likelihood p-value uses T(x)=−b(x)T(x) = -b(x). For the doubling rule, pd(x)≤αp_d(x) \le \alpha forces one tail to be at most α/2\alpha/2, and the two events have probability at most α/2\alpha/2 each. The tolerance δ\delta in line L6 can only enlarge the p-value, so it keeps the bound.

Proof: The binomial test returns the exact tail probabilities, and each p-value is validfull

We use the pseudocode of the page. Let X∼Binomial(n,p0)X \sim \text{Binomial}(n, p_0) and write b(k)=(nk)p0k(1−p0)n−kb(k) = \binom{n}{k} p_0^k (1 - p_0)^{n-k} for k=0,…,nk = 0, \ldots, n. All arithmetic is exact in this proof; the last part says what changes in floating point.

Claim 1 (the returned values). Line L1 sets w[k]=b(k)w[k] = b(k). Lines L2 and L3 give Phi(x)=∑k≥xb(k)=Pp0(X≥x)P_{hi}(x) = \sum_{k \ge x} b(k) = P_{p_0}(X \ge x) and Plo(x)=∑k≤xb(k)=Pp0(X≤x)P_{lo}(x) = \sum_{k \le x} b(k) = P_{p_0}(X \le x). Lines L4 and L5 return these for the one-sided alternatives. Lines L6 to L8 return, for δ=0\delta = 0,

pml(x)=∑k:b(k)≤b(x)b(k)=Pp0(b(X)≤b(x)),p_{ml}(x) = \sum_{k : b(k) \le b(x)} b(k) = P_{p_0}\big(b(X) \le b(x)\big),

which is at most 11, so the minimum in line L8 has no effect in exact arithmetic. The doubling rule of the code returns pd(x)=min⁡{1,2min⁡(Plo(x),Phi(x))}p_{d}(x) = \min\{1, 2 \min(P_{lo}(x), P_{hi}(x))\}. These are the definitions on the page. □\square

Lemma (a tail p-value is valid). Let XX take finitely many values, let TT be any real function of XX, and let p(x)=P(T(X)≥T(x))p(x) = P(T(X) \ge T(x)). Then P(p(X)≤u)≤uP(p(X) \le u) \le u for every u∈[0,1]u \in [0, 1].

Proof. Let A={x:p(x)≤u}A = \{x : p(x) \le u\} be the set of values in the support with a p-value at most uu. If AA is empty, the probability is 00. Otherwise AA is finite, so it has an element x∗x^* with the smallest value of TT. Each x∈Ax \in A has T(x)≥T(x∗)T(x) \ge T(x^*), so A⊆{x:T(x)≥T(x∗)}A \subseteq \{x : T(x) \ge T(x^*)\}. Hence P(X∈A)≤P(T(X)≥T(x∗))=p(x∗)≤uP(X \in A) \le P(T(X) \ge T(x^*)) = p(x^*) \le u. □\square

Claim 2 (validity). Under H0H_0, for every α∈[0,1]\alpha \in [0, 1], each of the four p-values satisfies Pp0(p(X)≤α)≤αP_{p_0}(p(X) \le \alpha) \le \alpha. So the test that rejects when p(x)≤αp(x) \le \alpha has size at most α\alpha.

Proof. Apply the lemma with these choices of TT.

  • PhiP_{hi}: take T(x)=xT(x) = x.
  • PloP_{lo}: take T(x)=−xT(x) = -x.
  • pmlp_{ml}: take T(x)=−b(x)T(x) = -b(x). Then T(X)≥T(x)T(X) \ge T(x) if and only if b(X)≤b(x)b(X) \le b(x).
  • pdp_d: if pd(x)≤αp_d(x) \le \alpha then Plo(x)≤α/2P_{lo}(x) \le \alpha/2 or Phi(x)≤α/2P_{hi}(x) \le \alpha/2. By the lemma each of these events has probability at most α/2\alpha/2, so their union has probability at most α\alpha. □\square

Claim 3 (the tolerance keeps validity). With δ>0\delta > 0 in line L6, the code returns pδ(x)=Pp0(b(X)≤(1+δ)b(x))≥pml(x)p_\delta(x) = P_{p_0}(b(X) \le (1 + \delta) b(x)) \ge p_{ml}(x). So {x:pδ(x)≤α}⊆{x:pml(x)≤α}\{x : p_\delta(x) \le \alpha\} \subseteq \{x : p_{ml}(x) \le \alpha\}, and Claim 2 gives P(pδ(X)≤α)≤αP(p_\delta(X) \le \alpha) \le \alpha. A larger δ\delta can only make the test more conservative. Its purpose is to count two exactly equal probabilities, such as b(k)b(k) and b(n−k)b(n - k) when p0=1/2p_0 = 1/2, as equal after rounding. □\square

Floating point. The code forms each b(k)b(k) as exp⁡\exp of a sum of lgamma⁡\operatorname{lgamma} values and logarithms, so each term has a small relative error that grows with the size of the logarithms, and math.fsum adds the terms with one rounding. The upper and lower tails are summed directly, so a small tail is not computed as 11 minus a number close to 11. The tests compare the result with exact Fraction sums to 10−1210^{-12} for n≤25n \le 25, and to a relative 10−910^{-9} for a tail near 10−3710^{-37} at n=1000n = 1000.

Cost. Line L1 does n+1n + 1 evaluations of three lgamma⁡\operatorname{lgamma} values, one exp⁡\exp and O(1)O(1) other operations. Lines L2, L3 and L7 each scan the list once. So the time is Θ(n)\Theta(n) in the real-RAM model with lgamma⁡\operatorname{lgamma} and exp⁡\exp as unit operations, and the list uses Θ(n)\Theta(n) space. □\square

Complexity

Line L1 does n+1n + 1 evaluations, each with three lgamma⁡\operatorname{lgamma} values, two logarithms reused across kk and one exp⁡\exp. Lines L2, L3 and L7 are linear scans. So the time is Θ(n)\Theta(n) and the extra space is Θ(n)\Theta(n) for the list ww. A one-sided p-value alone can be found without the list: Phi(x)=Ip0(x,n−x+1)P_{hi}(x) = I_{p_0}(x, n - x + 1), the regularized incomplete beta function, which a continued fraction evaluates without a sum of nn terms. The Clopper-Pearson interval uses this identity. For the two-sided rule the terms b(k)b(k) fall on each side of the mode, so a binary search can find the cut on the other side of the mode, but the sum itself still costs Θ(n)\Theta(n) terms in the simple form. For a quick upper bound with no sum, the Chernoff bound gives Phi(x)≤exp⁡(−nD(x/n ∥ p0))P_{hi}(x) \le \exp(-n D(x/n \,\Vert\, p_0)) for x≥np0x \ge n p_0, where DD is the binary relative entropy; see binomial tail bounds. A bound is not a p-value, but it is a valid conservative one.

Properties

  • Exact. The null law is exact for every nn. No large-sample condition such as np0≥5n p_0 \ge 5 is needed.
  • Conservative. The size is at most α\alpha, and equals α\alpha only at the attainable values. For n=10n = 10, p0=1/2p_0 = 1/2 and α=0.05\alpha = 0.05, the one-sided size is 0.01070.0107.
  • Power. The family Binomial(n,p)\text{Binomial}(n, p) has a monotone likelihood ratio in xx, so the test that rejects for x≥cx \ge c is uniformly most powerful among the tests of its own size against p>p0p > p_0, by the Karlin-Rubin theorem. With n=20n = 20, p0=1/2p_0 = 1/2 and α=0.05\alpha = 0.05, it rejects for x≥15x \ge 15 (size 0.02070.0207), and its power at p=0.75p = 0.75 is 0.6170.617. The randomized test that also rejects at x=14x = 14 with probability 0.7930.793 has size exactly 0.050.05 and power 0.7510.751. No uniformly most powerful test exists against the two-sided alternative.
  • The two-sided rule matters. For asymmetric nulls the two rules can disagree at α=0.05\alpha = 0.05, as the example shows. Say which one you use.
  • Discrete p-value. The p-value takes at most n+1n + 1 values, so its null law is not uniform. It is stochastically larger than uniform, which is the meaning of the validity bound.

Variants and improvements

  • Mid-p value. Pp0(X>x)+12Pp0(X=x)P_{p_0}(X > x) + \tfrac{1}{2} P_{p_0}(X = x) (Lancaster 1961). It is less conservative and its null mean is 1/21/2, but its size can exceed α\alpha slightly. For n=10n = 10, p0=0.2p_0 = 0.2 and x=4x = 4, the mid-p value is 0.07680.0768, against Phi(4)=0.1209P_{hi}(4) = 0.1209.
  • Randomized test. Reject on the boundary outcome with a probability chosen to make the size exactly α\alpha, as in the power example. It is optimal in theory but rarely used, since two analysts with the same data can reach different decisions.
  • Normal approximation. The score statistic z=(x−np0)/np0(1−p0)z = (x - n p_0)/\sqrt{n p_0 (1 - p_0)} is approximately standard normal for large nn; it is the score test and a form of the z-test. Its size can be far from α\alpha when np0n p_0 is small. A continuity correction subtracts 1/21/2 from ∣x−np0∣\lvert x - n p_0 \rvert.
  • Inverting the test. The set of p0p_0 that the test does not reject is a confidence set, by test-interval duality. The doubling rule gives the Clopper-Pearson interval. The minimum-likelihood rule gives the Sterne interval, which need not be an interval: for n=30n = 30 and x=1x = 1, the set of p0p_0 not rejected at α=0.05\alpha = 0.05 is about (0.0017,0.1632)(0.0017, 0.1632) together with the short piece (0.1751,0.1772)(0.1751, 0.1772), by a scan of p0p_0 on a grid of step 10−610^{-6}. Blaker (2000) gives a rule whose inversion behaves better.
  • Special cases. The sign test is a binomial test with p0=1/2p_0 = 1/2 on the signs of paired differences, and the exact McNemar test is a binomial test on the discordant pairs.

When to use it

Use it for a single proportion when the trials are independent with a common pp and nn was fixed in advance, and above all when nn is small or p0p_0 is near 0 or 1, where the normal approximation fails. With large nn and p0p_0 away from the ends, the score test gives nearly the same answer. To report an effect, pair the test with a confidence interval: Clopper-Pearson for a guarantee at every pp, or Wilson for intervals that are shorter on average.

Pitfalls

  • Which two-sided rule. R's binom.test uses the minimum-likelihood rule with a relative tolerance of 10−710^{-7}. Other software doubles the smaller tail. Results differ for p0≠1/2p_0 \ne 1/2.
  • Subtracting from 1. 1−Plo(x−1)1 - P_{lo}(x - 1) loses all digits when the upper tail is small. Sum the tail directly, as line L2 does.
  • The stopping rule. The p-value depends on how the data were collected. For 9 heads and 3 tails with p0=1/2p_0 = 1/2 and the one-sided alternative, a fixed n=12n = 12 gives P(X≥9)=299/4096=0.0730P(X \ge 9) = 299/4096 = 0.0730. If the coin was instead tossed until the third tail, the count of heads is negative binomial and P(at least 9 heads)=67/2048=0.0327P(\text{at least 9 heads}) = 67/2048 = 0.0327. The likelihood is the same in both cases, but the p-values are not.
  • Dependence and heterogeneity. Clustered trials or a pp that varies between trials make the variance of XX larger than np(1−p)n p (1 - p), and the test then rejects too often.
  • Size is not α\alpha. Report the attained size or the p-value, not only "significant at 5%". Power and sample size calculations must use the attained size, which jumps as nn changes.

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.

binomial_exact.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binomial-test/. The authors are listed in prov/P6MXFM.jsonl.

import math

# Two outcomes whose probabilities differ by less than this relative amount
# count as equally likely in the two-sided rule. Exact ties (for example
# k and n - k when p0 = 1/2) can differ in the last bits after rounding.
RELATIVE_TOLERANCE = 1e-7


def binomial_pmf(n: int, p0: float) -> list[float]:
    """Return [P(X = k) for k = 0..n] for X ~ Binomial(n, p0).

    The terms are computed in log space with math.lgamma, so that neither
    the binomial coefficient nor the power of p0 overflows or underflows
    before the product is formed.
    """
    if p0 == 0.0:
        return [1.0] + [0.0] * n
    if p0 == 1.0:
        return [0.0] * n + [1.0]
    log_p, log_q = math.log(p0), math.log1p(-p0)
    log_n_fact = math.lgamma(n + 1)
    return [
        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(n + 1)
    ]


def binomial_test(
    x: int,
    n: int,
    p0: float,
    alternative: str = "two-sided",
    rule: str = "minlike",
) -> float:
    """Exact p-value of the binomial test of H0: p = p0.

    x successes in n independent trials. alternative is "greater"
    (H1: p > p0), "less" (H1: p < p0) or "two-sided" (H1: p != p0).
    For the two-sided test, rule "minlike" sums the probabilities of the
    outcomes that are at most as likely as x (the default, as in R's
    binom.test), and rule "double" doubles the smaller one-sided p-value.
    """
    if not (isinstance(x, int) and isinstance(n, int)) or n < 0 or not 0 <= x <= n:
        raise ValueError("need integers with 0 <= x <= n")
    if not 0.0 <= p0 <= 1.0:
        raise ValueError("p0 must be in [0, 1]")
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError("unknown alternative")
    if rule not in ("minlike", "double"):
        raise ValueError("unknown two-sided rule")
    w = binomial_pmf(n, p0)  # @line L1
    upper = math.fsum(w[x:])  # @line L2
    lower = math.fsum(w[: x + 1])  # @line L3
    if alternative == "greater":  # @line L4
        return min(1.0, upper)
    if alternative == "less":  # @line L5
        return min(1.0, lower)
    if rule == "double":
        return min(1.0, 2.0 * min(lower, upper))
    t = w[x] * (1.0 + RELATIVE_TOLERANCE)  # @line L6
    p = math.fsum(v for v in w if v <= t)  # @line L7
    return min(1.0, p)  # @line L8
binomial_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binomial-test/. The authors are listed in prov/P6MXFM.jsonl.

"""Entry point named after the slug. The code lives in binomial_exact.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from binomial_exact import RELATIVE_TOLERANCE, binomial_pmf, binomial_test

__all__ = ["RELATIVE_TOLERANCE", "binomial_pmf", "binomial_test"]
test_binomial_test.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binomial-test/. The authors are listed in prov/P6MXFM.jsonl.

import itertools
import math
from fractions import Fraction

import pytest

from binomial_test import binomial_pmf, binomial_test


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 exact_p_value(x: int, n: int, p: Fraction, alternative: str, rule: str) -> Fraction:
    w = exact_pmf(n, p)
    upper, lower = sum(w[x:]), sum(w[: x + 1])
    if alternative == "greater":
        return upper
    if alternative == "less":
        return lower
    if rule == "double":
        return min(Fraction(1), 2 * min(lower, upper))
    return sum(v for v in w if v <= w[x])


def test_page_examples() -> None:
    assert binomial_test(8, 10, 0.5) == pytest.approx(7 / 64, abs=1e-15)
    assert binomial_test(8, 10, 0.5, "greater") == pytest.approx(7 / 128, abs=1e-15)
    assert binomial_test(5, 10, 0.2, "greater") == pytest.approx(0.0327934976, abs=1e-12)
    assert binomial_test(5, 10, 0.2) == pytest.approx(0.0327934976, abs=1e-12)
    assert binomial_test(5, 10, 0.2, rule="double") == pytest.approx(0.0655869952, abs=1e-12)
    assert binomial_test(0, 10, 0.2) == pytest.approx(0.228248064, abs=1e-12)
    assert binomial_test(0, 10, 0.2, rule="double") == pytest.approx(0.2147483648, abs=1e-12)
    assert binomial_test(9, 12, 0.5, "greater") == pytest.approx(299 / 4096, abs=1e-15)


def test_against_exact_fractions() -> None:
    for p in (Fraction(1, 10), Fraction(1, 5), Fraction(1, 3), Fraction(1, 2), Fraction(3, 4)):
        for n in range(0, 26):
            for x in range(n + 1):
                for alternative in ("greater", "less", "two-sided"):
                    for rule in ("minlike", "double"):
                        want = exact_p_value(x, n, p, alternative, rule)
                        got = binomial_test(x, n, float(p), alternative, rule)
                        assert abs(got - float(want)) <= 1e-12, (x, n, p, alternative, rule)


def test_against_sequences() -> None:
    # Brute force: enumerate all 2^n outcome sequences of the n trials.
    p = Fraction(1, 3)
    for n in range(0, 13):
        prob = {}
        for seq in itertools.product((0, 1), repeat=n):
            k = sum(seq)
            prob[seq] = p**k * (1 - p) ** (n - k)
        for x in range(n + 1):
            greater = sum(v for s, v in prob.items() if sum(s) >= x)
            less = sum(v for s, v in prob.items() if sum(s) <= x)
            assert abs(binomial_test(x, n, 1 / 3, "greater") - float(greater)) <= 1e-12
            assert abs(binomial_test(x, n, 1 / 3, "less") - float(less)) <= 1e-12


def test_size_never_exceeds_alpha() -> None:
    # The exact null probability of the rejection region {x : p(x) <= alpha}.
    for p in (Fraction(1, 10), Fraction(1, 4), Fraction(1, 2), Fraction(2, 3)):
        for n in (1, 5, 10, 17, 30):
            w = exact_pmf(n, p)
            for alpha in (Fraction(1, 100), Fraction(1, 20), Fraction(1, 10)):
                for alternative in ("greater", "less", "two-sided"):
                    for rule in ("minlike", "double"):
                        size = sum(
                            w[x]
                            for x in range(n + 1)
                            if binomial_test(x, n, float(p), alternative, rule) <= float(alpha)
                        )
                        assert size <= alpha


def test_attained_size_example() -> None:
    w = exact_pmf(10, Fraction(1, 2))
    region = [x for x in range(11) if binomial_test(x, 10, 0.5, "greater") <= 0.05]
    assert region == [9, 10]
    assert sum(w[x] for x in region) == Fraction(11, 1024)


def test_tail_far_out() -> None:
    # The upper tail is summed directly, so a tiny p-value keeps its digits.
    want = Fraction(sum(math.comb(1000, k) for k in range(700, 1001)), 2**1000)
    got = binomial_test(700, 1000, 0.5, "greater")
    assert got == pytest.approx(float(want), rel=1e-9)
    assert got < 1e-37


def test_edges() -> None:
    assert binomial_test(0, 0, 0.3) == 1.0
    assert binomial_test(0, 5, 0.0) == 1.0
    assert binomial_test(1, 5, 0.0, "greater") == 0.0
    assert binomial_test(5, 5, 1.0) == 1.0
    assert binomial_test(4, 5, 1.0, "less") == 0.0
    assert binomial_pmf(3, 0.5) == pytest.approx([1 / 8, 3 / 8, 3 / 8, 1 / 8])
    for bad in ((6, 5, 0.5), (-1, 5, 0.5), (2, 5, 1.5)):
        with pytest.raises(ValueError):
            binomial_test(*bad)
    with pytest.raises(ValueError):
        binomial_test(2, 5, 0.5, "both")


def test_monotone_in_x() -> None:
    values = [binomial_test(x, 40, 0.3, "greater") for x in range(41)]
    assert all(a >= b for a, b in zip(values, values[1:]))

History

John Arbuthnot (1710) noted that in each of the 82 years from 1629 to 1710 more boys than girls were christened in London, and that under even chances this has probability (1/2)82(1/2)^{82}. This is the first recorded significance test, and it is a one-sided binomial test, or a sign test. The Neyman-Pearson theory of the 1930s put the test in its modern form, with a fixed level and the optimality of the one-sided test. Lancaster (1961) proposed the mid-p value to reduce the conservatism of discrete tests. The question of the two-sided p-value for asymmetric discrete nulls has no single answer; textbooks such as Agresti's give both rules.

References

  1. Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Section 1.4 (statistical inference for binomial parameters, the exact test and the mid p-value) and Chapter 16 (small-sample exact inference)
  2. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 8.3 (methods of evaluating tests, the size of a test and p-values)
  3. E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 3 (uniformly most powerful tests, p-values and families with monotone likelihood ratio)
  4. John Arbuthnot, An argument for Divine Providence, taken from the constant regularity observed in the births of both sexes, Philosophical Transactions of the Royal Society 27, 1710, pp. 186 to 190 (82 years of christenings in London, each with more males than females)
  5. H. O. Lancaster, Significance tests in discrete distributions, Journal of the American Statistical Association 56(294), 1961, The whole paper (the mid-p value)

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