Algorithmcore
Fisher's exact test
Also called Fisher-Irwin test.
Tests independence in a 2 x 2 table exactly, from the hypergeometric distribution of one cell given the margins. It stays valid for small counts.
- Time
- Θ(n) worstΘ(m) best
- Space
- Θ(m) extra
- Where
- m = the number of tables with the observed margins (at most n + 1); n = the total count
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald A. Fisher, J. O. Irwin, Frank Yates, 1935
Fisher's exact test checks whether two binary variables are independent, or whether two groups have the same success probability, from the four counts of a table. It conditions on both row totals and both column totals. Given these margins, the whole table is fixed by its top-left cell, and under the null hypothesis that cell has a hypergeometric law that contains no unknown parameter. The p-value is a tail sum of that law, so the test is valid for every sample size, however small the counts. The code computes the hypergeometric weights as exact integers, so the p-values have no rounding error before the final division.
In plain words
A lady says she can tell whether milk or tea went into the cup first. You give her 8 cups, 4 of each kind, and she must pick the 4 with milk first. If she is only guessing, every choice of 4 cups out of 8 is equally likely, and there are 70 such choices. Only one of them is fully correct. So if she gets all 4 right, the chance of doing that well by luck is . Fisher's test does this counting for any table: keep the row and column totals fixed, count how many ways each table can arise, and add up the share of tables that are at least as extreme as the one you saw.
The problem
Model. A table of counts
| column 1 | column 2 | total | |
|---|---|---|---|
| row 1 | |||
| row 2 | |||
| total |
arises from two independent binomial rows ( and fixed), from one multinomial sample ( fixed), or from a design with both margins fixed.
Hypotheses. : the rows have the same probability of column 1 (equivalently, the two variables are independent, or the odds ratio equals 1). Alternatives: ("greater", large ), ("less") or (two-sided).
Statistic. The top-left count .
Null distribution. Conditional and exact. Given all margins, takes the values from to with
the hypergeometric law. The common success probability cancels, as the correctness proof shows.
Rejection rule and size. Reject when . The conditional size is at most for every set of margins, so the unconditional size is also at most . Because the conditional law is discrete, the size is usually well below ; see Properties.
P-values. for "greater", for "less", and for the two-sided test the minimum-likelihood rule , the total probability of the tables that are at most as likely as the observed one. This is the rule of R's fisher.test and of the code. Doubling the smaller tail is the other common rule; it can differ.
Sensitivity and power. Under the alternative the conditional law is , which depends only on the odds ratio. The one-sided test is the uniformly most powerful conditional test, but the conditioning costs power against the unconditional alternatives; see Properties.
The algorithm
FISHER-EXACT(a, b, c, d, alternative)- 1
r1 ← a + b; r2 ← c + d; c1 ← a + c; lo ← max(0, c1 - r2); hi ← min(r1, c1) - 2
w[lo] ← C(r1, lo) · C(r2, c1 - lo) - 3
for k ← lo to hi - 1 - 4
w[k + 1] ← w[k] · (r1 - k)(c1 - k) / ((k + 1)(r2 - c1 + k + 1)) ▷ exact integer division - 5
N ← w[lo] + ... + w[hi] ▷ equals C(n, c1) - 6
if alternative = greater then return (w[a] + ... + w[hi]) / N - 7
if alternative = less then return (w[lo] + ... + w[a]) / N - 8
return (sum of w[k] over all k with w[k] ≤ w[a]) / N
All values in lines L2 to L8 are exact integers. Line L4 uses the ratio of consecutive terms, so the loop needs one multiplication and one division per table instead of two binomial coefficients. The comparison in line L8 is exact, so two tables with equal probability are always treated as tied; floating-point code needs a tolerance here, as the binomial test does. The code returns the Fraction on request, or the correctly rounded float of it.
Example
The lady tasting tea. Table : rows are the true kind of cup, columns are her answer. The margins are all 4, so runs from 0 to 4 with weights , total . Line L4 gives them in turn: , , and so on. The one-sided p-value is . The two-sided value is . With 3 of 4 right, the one-sided value would be : the design cannot reach significance unless she is perfect.
Convictions of twins (Fisher 1935). Of 13 monozygotic twins of convicted criminals, 10 had a twin who was also convicted; of 17 dizygotic twins, 2 had. The table is with , , , . The weights for are
6188, 160888, 1516944, 6952660, 17381650, 25029576, 21237216, 10618608, 3063060, 486200, 38896, 1326, 13,
with total . So , which is about . The two-sided minimum-likelihood value adds the tables with weight at most 38896, which are (6188) on the other side, so . Doubling would give .
A one-sided result that is not two-sided. For , and . At only the one-sided test rejects; choose the alternative before seeing the data.
Against the chi-squared test. For , , Fisher's two-sided p-value is and the one-sided one is . The chi-squared test of independence gives and ; with Yates's continuity correction, and , closer to Fisher's value.
All the fractions above are computed exactly by the code, and the tests check them.
Correctness
The full proof is in proofs/correctness.md. In each sampling model, the joint law of the table under is times a factor that depends only on the margins, so conditioning on the margins leaves (Vandermonde's identity gives the total). Line L4 is exact because is an identity of integers. Each p-value is a tail of a finite law, so the lemma on the binomial test page gives conditional validity, and averaging over the margins gives unconditional validity.
Proof: Given the margins the top-left cell is hypergeometric, the recurrence gives its exact weights, and each p-value is validfull
Write the table as with row totals , , first column total and . Let and be the smallest and largest values of the top-left cell that the margins allow, and for .
Claim 1 (the null law given the margins). In each of these three sampling models, under the null hypothesis, the conditional law of the top-left cell given all four margins is
and it does not depend on any unknown parameter.
- Two independent binomial rows (fixed , ): and , independent, with .
- One multinomial sample (fixed ): the four cells are multinomial with probabilities , and is independence, .
- Both margins fixed by design, as in the tea experiment, with the "first column" labels assigned to the units at random: every set of units is equally likely.
Proof. Binomial rows: for in range,
Summing over and using Vandermonde's identity gives . Dividing, the factor with cancels. Multinomial: given the row totals, the two rows are independent binomials with success probabilities and , which under independence both equal ; so the first case applies. Fixed margins: of the equally likely sets, exactly put of the chosen units in row 1 and in row 2.
Claim 2 (lines L2 to L5 compute the weights exactly). Line L2 sets by its definition. For ,
All four factors are positive in this range: , , and because . So , an identity of integers. The left side is therefore a multiple of , and the integer division in line L4 is exact. By induction on , line L4 produces for every in range. Line L5 forms by Vandermonde's identity. No rounding happens anywhere.
Claim 3 (lines L6 to L8 return the p-values). With the index of the observed table, the three sums are
which are , and under the law of Claim 1. Because and are exact integers, the comparison in line L8 decides ties correctly; no tolerance is needed. The float result is with Python's correctly rounded integer division.
Claim 4 (conditional and unconditional validity). For every and each of the three p-values, under , and hence without conditioning.
Proof. Given the margins, takes finitely many values with the law of Claim 1, and each p-value has the form with , or . The lemma on the binomial test correctness page (a tail p-value over a finite space is valid) gives the conditional bound. Taking the expectation over the margins gives .
The unconditional size is usually well below , because the conditional size is below for every set of margins. The page measures it for two rows of 10.
Claim 5 (the one-sided test is the right conditional test). In the binomial-rows model with , arbitrary, let be the odds ratio. Then
which depends only on . For the likelihood ratio times a constant is increasing in . So the conditional family has a monotone likelihood ratio in , and by the Karlin-Rubin theorem the test that rejects for large is uniformly most powerful for against , among the tests whose conditional size is at most its own conditional size. (Exact size needs randomization at the boundary value, as for the binomial test.)
Proof. . Taking out the factors that do not depend on leaves , and conditioning divides by the sum over .
Cost. Line L2 computes two binomial coefficients with arithmetic operations. Lines L3 and L4 do steps, where , each with a fixed number of operations. Lines L5 to L8 are sums over at most terms. So the code does operations on integers and integers are stored. Each weight is at most , so it has at most bits, and an operation of an -bit integer with a small one costs bit operations; in bit operations the time is .
Complexity
Line L2 takes arithmetic operations, and lines L3 to L8 take , where is the number of tables with the observed margins. So the count of operations is and the extra space is integers. Each weight is below , so on a machine with fixed-size words every operation on a weight costs bit operations, and the total is bit operations. For in the thousands this is still fast; the tests run a table with in exact arithmetic. A floating-point version with weights from costs operations but needs a tolerance in line L8.
Properties
- Exact and conditional. The size is at most given every set of margins. The tests check this in exact arithmetic for all margins with .
- Conservative unconditionally. For two binomial rows of 10 trials with a common , the two-sided test at rejects for 34 of the 121 possible tables, and its unconditional size, measured on a grid of with step 0.001, is at most , reached at . The one-sided test rejects 23 tables and has size at most . These are measured on the grid, not proved maxima.
- Power. The one-sided test is uniformly most powerful among conditional tests, by the Karlin-Rubin theorem applied to the conditional family , and with randomization it is uniformly most powerful unbiased for (Lehmann and Romano, Chapter 4). Against two binomial rows it loses power to unconditional tests. For rows of 10, with and , the one-sided Fisher test at has power .
- Symmetric in the roles of rows and columns. Transposing the table, or swapping both rows and columns, does not change any p-value. Swapping only the rows exchanges "greater" and "less".
- Inverting the test. The conditional law also gives an exact confidence interval for the odds ratio, by test-interval duality, and the conditional maximum likelihood estimate of .
Variants and improvements
- Boschloo's test. Use Fisher's p-value as the statistic, but find the cut-off from the unconditional law, maximized over the common (Boschloo 1970). It is never less powerful than Fisher's test. For rows of 10 and the one-sided test at , the largest Fisher p-value cut-off whose size stayed below 0.05 on the grid was (size ), so the test rejects 27 tables instead of 23, and its power at rises from to ; at it rises from to . These numbers are computed exactly per table and maximized over a grid of .
- Barnard's test. An unconditional test that orders the tables by a statistic such as the pooled z statistic and maximizes the size over the nuisance (Barnard 1945). It is more powerful than Fisher's test in many cases, at a higher cost: a search over for every candidate table.
- Mid-p value. . For the twins it is . It is less conservative, but its size can exceed .
- Larger tables. The Freeman-Halton extension sums the multivariate hypergeometric probabilities of all tables with the observed margins that are at most as likely as the observed one. The number of tables grows fast, and network algorithms or Monte Carlo sampling are used.
- Stratified tables. Several tables with a common odds ratio are combined by conditioning on the margins of each; the exact conditional test and the Mantel-Haenszel test do this.
- Paired data. For matched pairs, use the McNemar test instead; Fisher's test assumes independent units.
When to use it
Use it for a table when some expected counts are small, so that the chi-squared approximation is doubtful, and in designs where both margins are fixed, such as the tea experiment, where it is exactly right. With large counts it agrees with the chi-squared test with continuity correction. When the two rows are independent binomial samples and power matters, an unconditional test such as Boschloo's is a better choice at the same guaranteed level. For an effect size, report the odds ratio with an exact or a likelihood interval.
Pitfalls
- Small size is not a guarantee of good power. Because the test is conservative, a nominal 5% test can have actual size near 1% to 2%, and the sample size needed for a given power is larger than a calculation at size 5% suggests.
- Which two-sided rule. Software differs: R uses the minimum-likelihood rule with a relative tolerance on the probabilities; some packages double the one-sided value. For the twins the two rules give and .
- Floating-point ties. A floating-point implementation can miss ties between tables with equal probability, which changes the two-sided p-value. Exact integer weights, as here, avoid this.
- Dependence. Paired or clustered units break the hypergeometric law. Use McNemar's test or a model for clusters.
- The choice of one side after the fact. As the second example shows, picking "greater" after seeing a large halves the p-value in effect.
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/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.
import math
from fractions import Fraction
def hypergeometric_weights(r1: int, r2: int, c1: int) -> tuple[int, list[int]]:
"""Return (lo, w) with w[i] = C(r1, lo + i) * C(r2, c1 - lo - i) as exact integers.
w[i] is the number of ways to choose the c1 items of the first column so
that lo + i of them fall in the first row. The list covers every possible
value of the top-left cell, from lo = max(0, c1 - r2) to min(r1, c1). Each
term comes from the one before by the ratio of consecutive binomial
coefficients, and the integer division is exact.
"""
lo, hi = max(0, c1 - r2), min(r1, c1)
w = [math.comb(r1, lo) * math.comb(r2, c1 - lo)] # @line L2
for k in range(lo, hi): # @line L3
w.append(w[-1] * (r1 - k) * (c1 - k) // ((k + 1) * (r2 - c1 + k + 1))) # @line L4
return lo, w
def fisher_exact(
a: int,
b: int,
c: int,
d: int,
alternative: str = "two-sided",
exact: bool = False,
) -> float | Fraction:
"""P-value of Fisher's exact test for the 2 x 2 table [[a, b], [c, d]].
Under the null hypothesis of independence (or equal proportions in the
two rows), the top-left cell has the hypergeometric law given the row and
column totals. alternative is "greater" (odds ratio > 1, large a), "less"
(odds ratio < 1, small a) or "two-sided", which sums the probabilities of
the tables that are at most as likely as the observed one. The weights are
exact integers, so the two-sided comparison needs no tolerance. With
exact=True the result is a Fraction; otherwise it is the correctly rounded
float of that Fraction.
"""
for v in (a, b, c, d):
if not isinstance(v, int) or v < 0:
raise ValueError("table entries must be non-negative integers")
if alternative not in ("two-sided", "greater", "less"):
raise ValueError("unknown alternative")
r1, r2, c1 = a + b, c + d, a + c # @line L1
lo, w = hypergeometric_weights(r1, r2, c1)
total = sum(w) # @line L5
i = a - lo
if alternative == "greater": # @line L6
num = sum(w[i:])
elif alternative == "less": # @line L7
num = sum(w[: i + 1])
else:
num = sum(v for v in w if v <= w[i]) # @line L8
return Fraction(num, total) if exact else num / total
fisher_exact_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.
"""Entry point named after the slug. The code lives in fisher_exact.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from fisher_exact import fisher_exact, hypergeometric_weights
__all__ = ["fisher_exact", "hypergeometric_weights"]
test_fisher_exact_test.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.
import itertools
import math
from fractions import Fraction
import pytest
from fisher_exact_test import fisher_exact, hypergeometric_weights
def test_page_examples() -> None:
cases = {
(4, 0, 0, 4): (Fraction(1, 70), Fraction(1), Fraction(1, 35)),
(10, 3, 2, 15): (Fraction(619, 1330665), None, Fraction(3571, 6653325)),
(1, 9, 11, 3): (None, Fraction(41, 29716), Fraction(41, 14858)),
(7, 2, 3, 8): (Fraction(293, 8398), None, Fraction(293, 4199)),
(12, 5, 7, 16): (Fraction(67703, 4989450), None, Fraction(118933, 4989450)),
}
for table, expected in cases.items():
for alt, want in zip(("greater", "less", "two-sided"), expected):
if want is not None:
assert fisher_exact(*table, alt, exact=True) == want
assert fisher_exact(*table, alt) == float(want)
def test_weights_are_products_of_binomials() -> None:
for r1 in range(0, 25):
for r2 in range(0, 25):
for c1 in range(0, r1 + r2 + 1):
lo, w = hypergeometric_weights(r1, r2, c1)
want = [math.comb(r1, k) * math.comb(r2, c1 - k) for k in range(lo, min(r1, c1) + 1)]
assert w == want
assert sum(w) == math.comb(r1 + r2, c1)
def brute_force(a: int, b: int, c: int, d: int) -> dict[str, Fraction]:
# Label n items; the first r1 form row 1. Every choice of the c1 items in
# column 1 is equally likely under the null. Count the choices.
r1, n, c1 = a + b, a + b + c + d, a + c
counts: dict[int, int] = {}
for chosen in itertools.combinations(range(n), c1):
k = sum(1 for i in chosen if i < r1)
counts[k] = counts.get(k, 0) + 1
total = sum(counts.values())
return {
"greater": Fraction(sum(v for k, v in counts.items() if k >= a), total),
"less": Fraction(sum(v for k, v in counts.items() if k <= a), total),
"two-sided": Fraction(sum(v for v in counts.values() if v <= counts[a]), total),
}
def test_against_enumeration_of_labelings() -> None:
checked = 0
for n in range(0, 9):
for a, b, c in itertools.product(range(n + 1), repeat=3):
d = n - a - b - c
if d < 0:
continue
want = brute_force(a, b, c, d)
for alt, value in want.items():
assert fisher_exact(a, b, c, d, alt, exact=True) == value
checked += 1
assert checked == 495
def test_conditional_size_at_most_alpha() -> None:
# For every set of margins with n <= 20, the conditional rejection
# probability at alpha = 0.05 is at most 0.05, in exact arithmetic.
alpha = Fraction(1, 20)
for r1 in range(1, 11):
for r2 in range(1, 11):
for c1 in range(1, r1 + r2):
lo, w = hypergeometric_weights(r1, r2, c1)
total = sum(w)
for alt in ("greater", "less", "two-sided"):
size = sum(
w[i]
for i in range(len(w))
if fisher_exact(lo + i, r1 - lo - i, c1 - lo - i, r2 - c1 + lo + i, alt, exact=True) <= alpha
)
assert Fraction(size, total) <= alpha
def unconditional_size(reject: list[tuple[int, int]], p: float) -> float:
return math.fsum(
math.comb(10, x1) * math.comb(10, x2) * p ** (x1 + x2) * (1 - p) ** (20 - x1 - x2) for x1, x2 in reject
)
def test_unconditional_size_is_well_below_alpha() -> None:
# Two binomial rows with 10 trials each and a common p. Measured on a grid.
for alt, n_reject, max_size in (("two-sided", 34, 0.0127792), ("greater", 23, 0.0210953)):
reject = [(x1, x2) for x1 in range(11) for x2 in range(11) if fisher_exact(x1, 10 - x1, x2, 10 - x2, alt) <= 0.05]
assert len(reject) == n_reject
sizes = [unconditional_size(reject, k / 1000) for k in range(1, 1000)]
k = max(range(999), key=sizes.__getitem__)
assert (k + 1) / 1000 == 0.5
assert sizes[k] == pytest.approx(max_size, abs=1e-7)
exact_half = Fraction(sum(math.comb(10, x1) * math.comb(10, x2) for x1, x2 in reject), 2**20)
assert float(exact_half) == pytest.approx(sizes[k], rel=1e-12)
def rejection_probability(reject: list[tuple[int, int]], p1: float, p2: float) -> float:
return math.fsum(
math.comb(10, x1) * p1**x1 * (1 - p1) ** (10 - x1) * math.comb(10, x2) * p2**x2 * (1 - p2) ** (10 - x2)
for x1, x2 in reject
)
def test_boschloo_raised_level_and_power() -> None:
# Boschloo: reject when Fisher's one-sided p <= t, with t the largest
# attainable value whose unconditional size stays <= 0.05 on the grid.
pv = {(x1, x2): fisher_exact(x1, 10 - x1, x2, 10 - x2, "greater") for x1 in range(11) for x2 in range(11)}
grid = [k / 1000 for k in range(1, 1000)]
best = None
for t in sorted(set(pv.values())):
reject = [key for key, v in pv.items() if v <= t]
if max(rejection_probability(reject, p, p) for p in grid) > 0.05:
break
best = t
assert best == pytest.approx(0.0849012, abs=1e-7)
fisher = [key for key, v in pv.items() if v <= 0.05]
boschloo = [key for key, v in pv.items() if v <= best]
assert (len(fisher), len(boschloo)) == (23, 27) and set(fisher) < set(boschloo)
assert rejection_probability(fisher, 0.7, 0.2) == pytest.approx(0.62163, abs=1e-5)
assert rejection_probability(boschloo, 0.7, 0.2) == pytest.approx(0.73345, abs=1e-5)
assert rejection_probability(fisher, 0.6, 0.3) == pytest.approx(0.24736, abs=1e-5)
assert rejection_probability(boschloo, 0.6, 0.3) == pytest.approx(0.35856, abs=1e-5)
def test_symmetries() -> None:
for table in ((3, 7, 9, 1), (5, 5, 2, 8), (0, 4, 6, 2), (12, 5, 7, 16)):
a, b, c, d = table
for alt in ("greater", "less", "two-sided"):
p = fisher_exact(a, b, c, d, alt, exact=True)
assert fisher_exact(a, c, b, d, alt, exact=True) == p # transpose
assert fisher_exact(d, c, b, a, alt, exact=True) == p # swap rows and columns
assert fisher_exact(c, d, a, b, "greater", exact=True) == fisher_exact(a, b, c, d, "less", exact=True)
assert fisher_exact(c, d, a, b, "two-sided", exact=True) == fisher_exact(a, b, c, d, "two-sided", exact=True)
def test_large_table_is_exact() -> None:
# Equal row totals make the null law symmetric, so the two-sided value is
# twice the upper tail. A log-space sum gives an independent reference.
p = fisher_exact(300, 200, 150, 350, exact=True)
upper = fisher_exact(300, 200, 150, 350, "greater", exact=True)
assert p == 2 * upper
log_total = math.lgamma(1001) - math.lgamma(451) - math.lgamma(551)
def log_w(k: int) -> float:
return (
math.lgamma(501) - math.lgamma(k + 1) - math.lgamma(501 - k)
+ math.lgamma(501) - math.lgamma(451 - k) - math.lgamma(51 + k)
)
reference = math.fsum(math.exp(log_w(k) - log_total) for k in range(300, 451))
assert float(upper) == pytest.approx(reference, rel=1e-9)
assert float(upper) == pytest.approx(6.702494878e-22, rel=1e-9)
lo, w = hypergeometric_weights(500, 500, 450)
assert sum(w) == math.comb(1000, 450)
assert fisher_exact(300, 200, 150, 350) == float(p)
def test_errors() -> None:
with pytest.raises(ValueError):
fisher_exact(1, -1, 2, 3)
with pytest.raises(ValueError):
fisher_exact(1, 2, 3, 4, "both")
with pytest.raises(ValueError):
fisher_exact(1.0, 2, 3, 4) # type: ignore[arg-type]
History
R. A. Fisher described the test in the fifth edition of Statistical Methods for Research Workers (1934) and in "The logic of inductive inference" (1935), where he analysed J. Lange's data on the convictions of twins of criminals. The lady tasting tea appears in The Design of Experiments (1935). J. O. Irwin (1935) and Frank Yates (1934), who also proposed the continuity correction for the chi-squared test, reached the same test independently. G. A. Barnard (1945) proposed an unconditional alternative and later withdrew his preference for it in favour of conditioning; R. D. Boschloo (1970) gave the raised conditional level that bears his name.
References
- R. A. Fisher, The logic of inductive inference, Journal of the Royal Statistical Society 98(1), 1935, pp. 39 to 82 (the exact test for a 2 x 2 table, with the data on convictions of twins)
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 3 (inference for two-way contingency tables, with small-sample tests of independence) and Chapter 16 (small-sample exact inference)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 4 (unbiased tests, with the comparison of two binomial populations by a conditional test)
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 PNP35A Edit this page History Report an error Markdown