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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John Arbuthnot, H. O. Lancaster, 1710
The binomial test checks a hypothesis about the success probability of independent trials. It uses the count of successes in trials and the exact null law of , so it needs no normal approximation and is valid for every . 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. are independent Bernoulli trials, and is the number of successes, so with the binomial distribution. The number of trials is fixed before the data are seen.
Hypotheses. against one of (one-sided, "greater"), (one-sided, "less") or (two-sided).
Statistic. The observed count . Write for the null probability of successes.
Null distribution. Exact: under , for every .
P-values.
- Greater: .
- Less: .
- Two-sided, the minimum-likelihood rule: . The outcomes "at least as extreme" are those that are at most as likely under .
- Two-sided, the doubling rule: .
The two rules agree when , where the law is symmetric. For other they differ, and neither one is always the smaller (see the example).
Rejection rule. Reject at level when . The size is at most for every and (proved in Correctness). It equals only when happens to be one of the finitely many attainable tail sums, so the test is conservative.
The algorithm
BINOMIAL-TEST(x, n, p0, alternative)- 1
w[k] ← C(n, k) p0^k (1 - p0)^(n - k) for k = 0 .. n ▷ in log space with lgamma - 2
P_hi ← w[x] + w[x + 1] + ... + w[n] - 3
P_lo ← w[0] + w[1] + ... + w[x] - 4
if alternative = greater then return P_hi - 5
if alternative = less then return P_lo - 6
t ← w[x] · (1 + δ) ▷ δ = 10^-7 absorbs rounding in ties - 7
P ← sum of w[k] over all k with w[k] ≤ t - 8
return min(1, P)
Line L1 computes and then takes . This avoids the overflow of and the underflow of for large ; see binomial coefficient computation for the exact integer route. The cases and 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 .
Example
A fair coin. , , . The null probabilities are : 1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1, each over 1024. The one-sided p-value is . Line L6 sets , and the outcomes with are . So , which is also .
An asymmetric null. , . The null probabilities are:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.10737 | 0.26844 | 0.30199 | 0.20133 | 0.08808 | 0.02642 | 0.00551 | 0.00079 | 0.00007 | 0.000004 | 0.0000001 |
- : . No outcome below the mode has a probability as small as , so , while . At the minimum-likelihood rule rejects and the doubling rule does not.
- : and . The outcomes with are and , so . Here the minimum-likelihood rule gives the larger value.
Attained size. For , , the one-sided test at rejects for , because . Its size is , far below . The two-sided test rejects for , with size .
A small tail. For , , , the exact upper tail is . Line L2 returns this to 9 digits. Computing it as in double precision returned , 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 for some ordering of the finite sample space, then for every . The set is contained in the tail of its own smallest member , and that tail has probability . The one-sided p-values use , and the minimum-likelihood p-value uses . For the doubling rule, forces one tail to be at most , and the two events have probability at most each. The tolerance 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 and write for . All arithmetic is exact in this proof; the last part says what changes in floating point.
Claim 1 (the returned values). Line L1 sets . Lines L2 and L3 give and . Lines L4 and L5 return these for the one-sided alternatives. Lines L6 to L8 return, for ,
which is at most , so the minimum in line L8 has no effect in exact arithmetic. The doubling rule of the code returns . These are the definitions on the page.
Lemma (a tail p-value is valid). Let take finitely many values, let be any real function of , and let . Then for every .
Proof. Let be the set of values in the support with a p-value at most . If is empty, the probability is . Otherwise is finite, so it has an element with the smallest value of . Each has , so . Hence .
Claim 2 (validity). Under , for every , each of the four p-values satisfies . So the test that rejects when has size at most .
Proof. Apply the lemma with these choices of .
- : take .
- : take .
- : take . Then if and only if .
- : if then or . By the lemma each of these events has probability at most , so their union has probability at most .
Claim 3 (the tolerance keeps validity). With in line L6, the code returns . So , and Claim 2 gives . A larger can only make the test more conservative. Its purpose is to count two exactly equal probabilities, such as and when , as equal after rounding.
Floating point. The code forms each as of a sum of 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 minus a number close to . The tests compare the result with exact Fraction sums to for , and to a relative for a tail near at .
Cost. Line L1 does evaluations of three values, one and other operations. Lines L2, L3 and L7 each scan the list once. So the time is in the real-RAM model with and as unit operations, and the list uses space.
Complexity
Line L1 does evaluations, each with three values, two logarithms reused across and one . Lines L2, L3 and L7 are linear scans. So the time is and the extra space is for the list . A one-sided p-value alone can be found without the list: , the regularized incomplete beta function, which a continued fraction evaluates without a sum of terms. The Clopper-Pearson interval uses this identity. For the two-sided rule the terms 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 terms in the simple form. For a quick upper bound with no sum, the Chernoff bound gives for , where 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 . No large-sample condition such as is needed.
- Conservative. The size is at most , and equals only at the attainable values. For , and , the one-sided size is .
- Power. The family has a monotone likelihood ratio in , so the test that rejects for is uniformly most powerful among the tests of its own size against , by the Karlin-Rubin theorem. With , and , it rejects for (size ), and its power at is . The randomized test that also rejects at with probability has size exactly and power . 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 , as the example shows. Say which one you use.
- Discrete p-value. The p-value takes at most 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. (Lancaster 1961). It is less conservative and its null mean is , but its size can exceed slightly. For , and , the mid-p value is , against .
- Randomized test. Reject on the boundary outcome with a probability chosen to make the size exactly , 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 is approximately standard normal for large ; it is the score test and a form of the z-test. Its size can be far from when is small. A continuity correction subtracts from .
- Inverting the test. The set of 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 and , the set of not rejected at is about together with the short piece , by a scan of on a grid of step . Blaker (2000) gives a rule whose inversion behaves better.
- Special cases. The sign test is a binomial test with 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 and was fixed in advance, and above all when is small or is near 0 or 1, where the normal approximation fails. With large and 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 , or Wilson for intervals that are shorter on average.
Pitfalls
- Which two-sided rule. R's
binom.testuses the minimum-likelihood rule with a relative tolerance of . Other software doubles the smaller tail. Results differ for . - Subtracting from 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 and the one-sided alternative, a fixed gives . If the coin was instead tossed until the third tail, the count of heads is negative binomial and . The likelihood is the same in both cases, but the p-values are not.
- Dependence and heterogeneity. Clustered trials or a that varies between trials make the variance of larger than , and the test then rejects too often.
- Size is not . 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 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.
# 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 . 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
- 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)
- 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)
- 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)
- 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)
- 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.
| 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 P6MXFM Edit this page History Report an error Markdown