Algorithmintro
Bonferroni correction
Also called Bonferroni procedure, Bonferroni adjustment.
Tests each of m hypotheses at level alpha / m. By the union bound the family-wise error rate is at most alpha under any dependence.
- Time
- Θ(m) worst · best
- Space
- Θ(m) extra
- Where
- m = the number of hypotheses
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Carlo Emilio Bonferroni, Olive Jean Dunn, 1961
The Bonferroni correction is the simplest way to test hypotheses at once. It tests each hypothesis at level instead of , so it rejects when its p-value satisfies . Equivalently, it reports the adjusted p-value and rejects when . The union bound then shows that the family-wise error rate, the probability of one or more false rejections, is at most . This holds for every set of true nulls and every dependence between the tests, with no assumption except that each null p-value is valid. The price is power: the threshold falls like , and Holm's method rejects at least as much under the same conditions.
In plain words
If you run many tests and each one has a small chance of a false alarm, the chance of at least one false alarm grows with the number of tests. With twenty tests at the usual 5% level, it is about 64% when nothing is going on. The Bonferroni correction splits the allowed error between the tests. Each test gets an equal share, so if you run twenty tests, each one must pass a level twenty times stricter. The chance of at least one false alarm is then at most the sum of the shares, which is the level you wanted. This is true whatever the relation between the tests. The cost is that real effects must be much stronger to pass.
The problem
Input. P-values for hypotheses , and a level . The set of true nulls is , with elements. Each null p-value is valid: for all and all . Nothing is assumed about the joint law of the p-values.
Output. The set of rejected hypotheses and the adjusted p-values . For , is rejected exactly when , so the adjusted p-value is the smallest level at which the procedure rejects .
Error rate controlled. Strong control of the family-wise error rate: with the number of true nulls rejected, for every , and not only under the global null. It also controls the expected number of false rejections, , which is a stronger statement.
Dependence. Arbitrary. The control is exact in finite samples, as an inequality. It is attained: when the events , , are disjoint and every null p-value is uniform, the family-wise error rate is exactly .
The algorithm
BONFERRONI(p₁, …, p_m, α) ▷ p-values in [0, 1], level α- 1
c ← α / m ▷ the per-test level - 2
for i ← 1 to m do - 3
rejectᵢ ← (pᵢ ≤ c) - 4
p̃ᵢ ← min(1, m · pᵢ) ▷ the adjusted p-value - 5
return (reject, p̃)
The order of the p-values does not matter, and no sorting is needed.
Example
Fifteen p-values. Benjamini and Hochberg (1995) used these 15 p-values from a clinical trial: 0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000. Take .
| step | value |
|---|---|
| L1: | 0.003333 |
| L3: | true for 0.0001, 0.0004, 0.0019; false from 0.0095 on |
| L4: , first nine | 0.0015, 0.006, 0.0285, 0.1425, 0.3015, 0.417, 0.447, 0.516, 0.6885 |
| L4: last six | 1, 1, 1, 1, 1, 1 |
Bonferroni rejects 3 hypotheses. Nine of the raw p-values are below 0.05, so testing each at 0.05 would reject 9. Holm's method also rejects 3 here, and the Benjamini-Hochberg procedure at rejects 4, because it controls a weaker error rate.
How the threshold shrinks. The table gives, for independent tests at with all nulls true, the family-wise error rate with no correction, , and the per-test levels of Bonferroni and of Šidák, .
| no correction | Bonferroni | Šidák | |
|---|---|---|---|
| 1 | 0.05 | 0.05 | 0.05 |
| 5 | 0.2262 | 0.01 | 0.010206 |
| 10 | 0.4013 | 0.005 | 0.005116 |
| 20 | 0.6415 | 0.0025 | 0.002561 |
| 100 | 0.9941 | 0.0005 | 0.000513 |
The Šidák level is a little larger, but the two differ by less than 3% of at . On the 15 p-values above, the Šidák level is 0.0034137, and it rejects the same 3 hypotheses.
Correctness
The family-wise error event is the union over of the events . By the union bound its probability is at most , using only the validity of each null p-value. No independence is used, and is arbitrary, so the control is strong. The same sum bounds , by linearity of expectation. The bound is attained by the law in which with one uniform : each is uniform, and the events are disjoint. The correctness proof gives these steps and the equivalence of the two forms of the output. The tests check the attained case exactly, with fractions, on a grid.
Proof: The Bonferroni correction controls the family-wise error rate strongly under any dependence, and the bound is attainedfull
We prove that BONFERRONI controls the family-wise error rate at for every set of true nulls and every joint law of the p-values, that the bound cannot be improved without assumptions on the dependence, and that the two forms of the output agree. We also prove that the Šidák level gives an error rate of exactly under independence. All results here are proved; the tests check them by exact counting on grids and by simulation.
Setting. are hypotheses with p-values , and is the set of true nulls, with . For each , is valid: for all . is the number of false rejections.
Lemma 1 (what the lines compute). BONFERRONI rejects if and only if , and for this holds if and only if .
Proof. Line L1 sets and line L3 sets to the truth value of . For the second claim: if then , so . Conversely, if , the minimum is not 1, so it equals , and gives .
At every capped value satisfies , while can fail; this is why the equivalence needs , and why the level is in in practice.
Theorem 1 (strong control). For every and every joint law of with valid null p-values,
Proof. By Lemma 1, . By linearity of expectation, which needs no independence,
where the inequality is the validity of each null p-value at . Since takes values in , , and taking expectations gives . Finally .
The first inequality is Markov's inequality at 1, and the whole chain is the union bound with . Because is arbitrary, the control is strong, not only under the global null .
Theorem 2 (the bound is attained). Let and . There is a joint law in which every is uniform on and exactly.
Proof. Let be uniform on and for . Each is a rotation of on the circle of length 1, so it is uniform. The event is the event that lies in the arc taken modulo 1. These arcs have length and start at the distinct points , which are apart, so they overlap at most at their end points, a set of probability zero. So .
So no procedure that uses the threshold on every test can control the family-wise error rate at under arbitrary dependence: on this law, it has error rate . Bonferroni is the best single-step procedure with a common threshold when nothing is known about the dependence. The tests check Theorem 2 by exact counting, on a grid of values of with a multiple of , where each is uniform on .
Theorem 3 (Šidák under independence). If the null p-values are independent and uniform, and every is tested at , then , with equality when . Also .
Proof. By independence, . This is at least , with equality when . For the last claim, by Bernoulli's inequality , so , which is .
Under dependence Theorem 3 can fail. Šidák (1967) proved that for a normal vector with mean zero and any covariance, , which makes the two-sided tests based on such a vector valid at the Šidák level. We cite this result and do not prove it.
Termination and cost. The loop runs times and does a constant amount of work each time.
Complexity
On a real RAM, the loop at lines L2 to L4 does one comparison and one multiplication per hypothesis, so the time is in every case. The output takes space; a streaming version that reads the p-values one at a time and reports each decision uses extra space, but it must know in advance.
Numerical stability. There is no cancellation. Compare or , never , which loses all digits of a small . For the Šidák level, cancels for large : with and , it is about , a difference of two numbers near 1. The implementation computes it as , which keeps full relative accuracy.
Properties
- Strong FWER control under any dependence. Proved by the union bound, with no condition on the joint law.
- Single-step. The threshold of each test does not depend on the other p-values. Each decision can be made in isolation, in any order.
- Conservative under dependence. With positively dependent tests, the true family-wise error rate is below , often far below. If all p-values are equal, it is .
- Nearly exact under independence for small . With independent uniform nulls the error rate is , which is between and when .
- Dominated by Holm. Holm's method rejects every hypothesis that Bonferroni rejects, with the same guarantee.
- Controls the expected number of false rejections. , which bounds the per-family error rate as well.
Variants and improvements
- Weighted Bonferroni. Give the level with and . The union bound gives the same control. Weights can come from prior knowledge or from independent data, and they gain power when they put more of on the false nulls.
- Šidák correction. Test each hypothesis at . With independent tests the family-wise error rate under the global null is exactly . Šidák (1967) proved the inequality behind it for two-sided tests on a multivariate normal vector with any correlation, so it is valid there too. It can fail for other kinds of dependence, where Bonferroni cannot.
- Holm's step-down method. Sort the p-values and compare the -th smallest with . It is uniformly more powerful, with the same assumptions. See Holm-Bonferroni method.
- Hochberg's step-up method. The same thresholds used from the largest p-value down. It is more powerful again, but it needs independence or positive dependence. See Hochberg procedure.
- Resampling. The Westfall-Young procedure replaces by a quantile of the minimum p-value under permutations, which adapts to the dependence.
- Bonferroni confidence intervals. For parameters, use intervals at level each. All cover at the same time with probability at least . This is Dunn's use of the inequality. For all pairwise differences of normal means, Tukey's HSD is shorter, and for all contrasts, Scheffé's method.
When to use it
Use Bonferroni when the number of tests is small, when the dependence between the tests is unknown, and when the control of each false rejection matters, as in a clinical trial with a few primary end points. It is also the right choice when each decision must be made on its own, before the other p-values exist. When the p-values are all available, use Holm's method instead: it has the same guarantee and never rejects less. When is large and some false rejections are acceptable, control the false discovery rate instead, for example with the Benjamini-Hochberg procedure.
Pitfalls
- Counting the tests. is the number of tests that were done or could have been reported, not the number that look interesting. Choosing the tests after seeing the data, and correcting only for those, does not control the error rate.
- Weak and strong control are different. Bonferroni controls the error for every set of true nulls, but a single global test built from it, "reject the global null if any ", has low power against many small effects. Use Fisher's method for that question.
- Highly correlated tests. With strongly correlated statistics, as for nearby genetic markers, Bonferroni is very conservative. Permutation methods such as Westfall-Young can be much more powerful.
- Adjusted p-values above 1. can exceed 1. Cap it at 1, as line L4 does; a reported "adjusted p-value" of 3 is a bug.
- Not a statement about one test. A hypothesis that passes is not "significant at " in the usual sense; the guarantee is about the family. A result that fails it may still be a true effect: Bonferroni trades power for error control.
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/bonferroni-correction/. The authors are listed in prov/DBDQ24.jsonl.
"""The Bonferroni correction for m hypotheses, and the Sidak variant.
Bonferroni rejects H_i when p_i <= alpha / m. By the union bound the
family-wise error rate is at most (m_0 / m) alpha <= alpha under any
dependence. The adjusted p-value is min(1, m p_i), and H_i is rejected
exactly when it is at most alpha. The code works with float or with
fractions.Fraction inputs; with Fractions every result is exact.
"""
from collections.abc import Sequence
def bonferroni_correction(p: Sequence, alpha) -> tuple[list[bool], list]:
"""Return (reject, adjusted) for the p-values p at family-wise level alpha."""
m = len(p)
if m == 0:
return [], []
if any(not 0 <= v <= 1 for v in p): # also rejects NaN
raise ValueError("p-values must lie in [0, 1]")
if not 0 <= alpha <= 1:
raise ValueError("alpha must lie in [0, 1]")
level = alpha / m # @line L1
reject, adjusted = [], []
for v in p: # @line L2
reject.append(v <= level) # @line L3
adjusted.append(min(1, m * v)) # @line L4
return reject, adjusted # @line L5
def sidak_level(alpha: float, m: int) -> float:
"""The per-test level 1 - (1 - alpha)^(1/m) of the Sidak correction.
Computed as -expm1(log1p(-alpha) / m), which does not cancel for small alpha.
"""
import math
if m < 1:
raise ValueError("m must be at least 1")
return -math.expm1(math.log1p(-alpha) / m)
def sidak_correction(p: Sequence[float], alpha: float) -> tuple[list[bool], list[float]]:
"""Reject H_i when p_i <= 1 - (1 - alpha)^(1/m); adjusted p-value 1 - (1 - p_i)^m."""
import math
m = len(p)
if m == 0:
return [], []
level = sidak_level(alpha, m)
reject = [v <= level for v in p]
adjusted = [1.0 if v >= 1 else -math.expm1(m * math.log1p(-v)) for v in p]
return reject, adjusted
test_bonferroni_correction.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bonferroni-correction/. The authors are listed in prov/DBDQ24.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from bonferroni_correction import bonferroni_correction, sidak_correction, sidak_level
# The 15 p-values of the worked example of Benjamini and Hochberg (1995).
BH95 = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]
def test_worked_example_by_hand() -> None:
reject, adjusted = bonferroni_correction(BH95, 0.05)
# 0.05 / 15 = 0.00333..., so only the first three p-values are at most the level.
assert [i for i, r in enumerate(reject) if r] == [0, 1, 2]
assert adjusted[:4] == pytest.approx([0.0015, 0.006, 0.0285, 0.1425])
assert adjusted[-1] == 1
def test_exact_with_fractions() -> None:
p = [Fraction(1, 100), Fraction(1, 40), Fraction(1, 30), Fraction(1, 2)]
reject, adjusted = bonferroni_correction(p, Fraction(1, 20))
# The level is 1/80: only 1/100 is at most it.
assert reject == [True, False, False, False]
assert adjusted == [Fraction(1, 25), Fraction(1, 10), Fraction(2, 15), 1]
def test_boundary_is_rejected() -> None:
reject, _ = bonferroni_correction([Fraction(1, 40), Fraction(1, 2)], Fraction(1, 20))
assert reject == [True, False]
def test_adjusted_p_value_matches_rejections() -> None:
rng = random.Random(11)
for _ in range(200):
m = rng.randint(1, 12)
p = [Fraction(rng.randint(0, 400), 400) for _ in range(m)]
_, adjusted = bonferroni_correction(p, Fraction(1, 20))
# For alpha < 1 the cap at 1 does not matter; at alpha = 1 every capped value is "rejected".
for alpha in [Fraction(k, 100) for k in range(0, 100, 5)]:
reject, _ = bonferroni_correction(p, alpha)
assert reject == [a <= alpha for a in adjusted]
def test_invalid_input() -> None:
assert bonferroni_correction([], 0.05) == ([], [])
with pytest.raises(ValueError):
bonferroni_correction([0.2, 1.5], 0.05)
with pytest.raises(ValueError):
bonferroni_correction([0.2, float("nan")], 0.05)
with pytest.raises(ValueError):
bonferroni_correction([0.2], 1.5)
def test_union_bound_is_attained_exactly() -> None:
"""Reference law: p_i = (U + i/m) mod 1 with U uniform on a grid of N points.
Every p_i is uniform on the grid, and the events {p_i <= alpha/m} are disjoint, so the
family-wise error rate of Bonferroni is exactly alpha. We count over all N values of U.
"""
for m, n_grid, alpha in [(2, 40, Fraction(1, 10)), (4, 80, Fraction(1, 10)), (5, 100, Fraction(1, 20))]:
hits = 0
for u in range(1, n_grid + 1):
p = [Fraction((u + i * n_grid // m - 1) % n_grid + 1, n_grid) for i in range(m)]
reject, _ = bonferroni_correction(p, alpha)
hits += any(reject)
assert Fraction(hits, n_grid) == alpha
def test_exact_fwer_under_independence_on_a_grid() -> None:
"""All m nulls true, independent p-values uniform on {1/N, ..., N/N}: brute force over N^m points.
The family-wise error rate is 1 - (1 - c/N)^m, where c = #{k : k/N <= alpha/m}, and it is at most alpha.
"""
n_grid, alpha = 10, Fraction(2, 5)
for m in [1, 2, 3, 4]:
grid = [Fraction(k, n_grid) for k in range(1, n_grid + 1)]
hits = sum(any(bonferroni_correction(list(p), alpha)[0]) for p in itertools.product(grid, repeat=m))
exact = Fraction(hits, n_grid**m)
c = sum(1 for g in grid if g <= alpha / m)
assert exact == 1 - (1 - Fraction(c, n_grid)) ** m
assert exact <= alpha
def test_monte_carlo_strong_control_with_dependence() -> None:
"""m = 10, m_0 = 6 true nulls with equicorrelated normal statistics (rho = 0.5), 4 false nulls."""
rng = random.Random(2024)
nd = __import__("statistics").NormalDist()
m, m0, alpha, reps = 10, 6, 0.05, 20000
errors = 0
for _ in range(reps):
shared = rng.gauss(0, 1)
z = [math.sqrt(0.5) * shared + math.sqrt(0.5) * rng.gauss(0, 1) for _ in range(m)]
z = [zi + (3.0 if i >= m0 else 0.0) for i, zi in enumerate(z)]
p = [1 - nd.cdf(zi) for zi in z]
reject, _ = bonferroni_correction(p, alpha)
errors += any(reject[:m0])
fwer = errors / reps
# The union bound gives FWER <= (m0/m) alpha = 0.03. Three standard errors of a proportion near 0.03 are 0.0036.
assert fwer <= m0 / m * alpha + 0.0036
def test_sidak_is_exact_under_independence() -> None:
for m in [1, 2, 5, 20, 100]:
level = sidak_level(0.05, m)
assert 1 - (1 - level) ** m == pytest.approx(0.05, rel=1e-12)
assert level >= 0.05 / m # Sidak is never stricter than Bonferroni
assert sidak_level(0.05, 15) == pytest.approx(0.0034137, abs=1e-7)
reject, adjusted = sidak_correction(BH95, 0.05)
assert [i for i, r in enumerate(reject) if r] == [0, 1, 2]
assert adjusted[0] == pytest.approx(1 - (1 - 0.0001) ** 15, rel=1e-12)
assert adjusted[-1] == 1.0
def test_sidak_monte_carlo_fwer() -> None:
rng = random.Random(7)
m, reps = 8, 40000
level = sidak_level(0.05, m)
hits = sum(any(rng.random() <= level for _ in range(m)) for _ in range(reps))
# The exact FWER is 0.05; four standard errors are 0.0044.
assert abs(hits / reps - 0.05) < 0.0044
History
Carlo Emilio Bonferroni published his inequalities for the probability of a union of events in 1936, in a paper on the statistical theory of classes. The first of them, , is much older and goes back to Boole. Olive Jean Dunn used it in 1961 to build simultaneous confidence intervals for several means, each at level , and the name "Bonferroni correction" comes from this use. Šidák (1967) proved that, for normal vectors, the product of the marginal probabilities is a lower bound for the joint coverage, which gives the slightly larger per-test level . Holm (1979) showed that a sequential use of the same inequality rejects more, with the same guarantee.
References
- Olive Jean Dunn, Multiple comparisons among means, Journal of the American Statistical Association 56(293) (1961), pages 52 to 64, the intervals for m linear combinations of means at level alpha / m each, from the first Bonferroni inequality
- Zbyněk Šidák, Rectangular confidence regions for the means of multivariate normal distributions, Journal of the American Statistical Association 62(318) (1967), pages 626 to 633, the inequality P(all |X_i| <= c_i) >= product of P(|X_i| <= c_i) for a normal vector, which gives the level 1 - (1 - alpha)^(1/m)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 9, Section 9.1 (the family-wise error rate and the Bonferroni procedure)
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 DBDQ24 Edit this page History Report an error Markdown