Algorithm Search⌘K

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
Properties
deterministicnot exactonlineiterative
Origin
Carlo Emilio Bonferroni, Olive Jean Dunn, 1961

The Bonferroni correction is the simplest way to test mm hypotheses at once. It tests each hypothesis at level α/m\alpha/m instead of α\alpha, so it rejects HiH_i when its p-value satisfies pi≤α/mp_i \le \alpha/m. Equivalently, it reports the adjusted p-value p~i=min⁡(1,mpi)\tilde p_i = \min(1, mp_i) and rejects when p~i≤α\tilde p_i \le \alpha. The union bound then shows that the family-wise error rate, the probability of one or more false rejections, is at most (m0/m)α≤α(m_0/m)\alpha \le \alpha. 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 1/m1/m, 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 p1,…,pmp_1, \dots, p_m for hypotheses H1,…,HmH_1, \dots, H_m, and a level α∈(0,1)\alpha \in (0, 1). The set of true nulls is I0I_0, with m0=∣I0∣m_0 = |I_0| elements. Each null p-value is valid: P(pi≤u)≤uP(p_i \le u) \le u for all u∈[0,1]u \in [0, 1] and all i∈I0i \in I_0. Nothing is assumed about the joint law of the p-values.

Output. The set of rejected hypotheses {i:pi≤α/m}\{i : p_i \le \alpha/m\} and the adjusted p-values p~i=min⁡(1,mpi)\tilde p_i = \min(1, mp_i). For α<1\alpha < 1, HiH_i is rejected exactly when p~i≤α\tilde p_i \le \alpha, so the adjusted p-value is the smallest level at which the procedure rejects HiH_i.

Error rate controlled. Strong control of the family-wise error rate: with VV the number of true nulls rejected, P(V≥1)≤(m0/m)α≤αP(V \ge 1) \le (m_0/m)\alpha \le \alpha for every I0I_0, and not only under the global null. It also controls the expected number of false rejections, E[V]≤(m0/m)αE[V] \le (m_0/m)\alpha, which is a stronger statement.

Dependence. Arbitrary. The control is exact in finite samples, as an inequality. It is attained: when the events {pi≤α/m}\{p_i \le \alpha/m\}, i∈I0i \in I_0, are disjoint and every null p-value is uniform, the family-wise error rate is exactly (m0/m)α(m_0/m)\alpha.

The algorithm

  1. BONFERRONI(p₁, …, p_m, α) ▷ p-values in [0, 1], level α
  2. 1c ← α / m ▷ the per-test level
  3. 2for i ← 1 to m do
  4. 3rejectᵢ ← (pᵢ ≤ c)
  5. 4p̃ᵢ ← min(1, m · pᵢ) ▷ the adjusted p-value
  6. 5return (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 α=0.05\alpha = 0.05.

step value
L1: c=0.05/15c = 0.05/15 0.003333
L3: pi≤cp_i \le c true for 0.0001, 0.0004, 0.0019; false from 0.0095 on
L4: p~i=min⁡(1,15pi)\tilde p_i = \min(1, 15p_i), 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 q=0.05q = 0.05 rejects 4, because it controls a weaker error rate.

How the threshold shrinks. The table gives, for independent tests at α=0.05\alpha = 0.05 with all nulls true, the family-wise error rate with no correction, 1−0.95m1 - 0.95^m, and the per-test levels of Bonferroni and of Šidák, 1−0.951/m1 - 0.95^{1/m}.

mm no correction Bonferroni α/m\alpha/m Š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 α/m\alpha/m at α=0.05\alpha = 0.05. 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 i∈I0i \in I_0 of the events {pi≤α/m}\{p_i \le \alpha/m\}. By the union bound its probability is at most ∑i∈I0P(pi≤α/m)≤m0⋅α/m\sum_{i \in I_0}P(p_i \le \alpha/m) \le m_0 \cdot \alpha/m, using only the validity of each null p-value. No independence is used, and I0I_0 is arbitrary, so the control is strong. The same sum bounds E[V]E[V], by linearity of expectation. The bound is attained by the law in which pi=(U+i/m) mod 1p_i = (U + i/m) \bmod 1 with one uniform UU: each pip_i is uniform, and the events {pi≤α/m}\{p_i \le \alpha/m\} 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 (m0/m)α(m_0/m)\alpha 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 α\alpha under independence. All results here are proved; the tests check them by exact counting on grids and by simulation.

Setting. H1,…,HmH_1, \dots, H_m are hypotheses with p-values p1,…,pmp_1, \dots, p_m, and I0⊆{1,…,m}I_0 \subseteq \{1, \dots, m\} is the set of true nulls, with m0=∣I0∣m_0 = |I_0|. For each i∈I0i \in I_0, pip_i is valid: P(pi≤u)≤uP(p_i \le u) \le u for all u∈[0,1]u \in [0, 1]. V=∣{i∈I0:Hi rejected}∣V = |\{i \in I_0 : H_i \text{ rejected}\}| is the number of false rejections.

Lemma 1 (what the lines compute). BONFERRONI rejects HiH_i if and only if pi≤α/mp_i \le \alpha/m, and for α<1\alpha < 1 this holds if and only if p~i=min⁡(1,mpi)≤α\tilde p_i = \min(1, mp_i) \le \alpha.

Proof. Line L1 sets c=α/mc = \alpha/m and line L3 sets rejecti\text{reject}_i to the truth value of pi≤cp_i \le c. For the second claim: if pi≤α/mp_i \le \alpha/m then mpi≤αmp_i \le \alpha, so min⁡(1,mpi)≤α\min(1, mp_i) \le \alpha. Conversely, if min⁡(1,mpi)≤α<1\min(1, mp_i) \le \alpha < 1, the minimum is not 1, so it equals mpimp_i, and mpi≤αmp_i \le \alpha gives pi≤α/mp_i \le \alpha/m. □\square

At α=1\alpha = 1 every capped value satisfies p~i≤1\tilde p_i \le 1, while pi≤1/mp_i \le 1/m can fail; this is why the equivalence needs α<1\alpha < 1, and why the level is in (0,1)(0, 1) in practice.

Theorem 1 (strong control). For every I0I_0 and every joint law of (p1,…,pm)(p_1, \dots, p_m) with valid null p-values,

P(V≥1)≤E[V]≤m0mα≤α.P(V \ge 1) \le E[V] \le \frac{m_0}{m}\alpha \le \alpha.

Proof. By Lemma 1, V=∑i∈I01{pi≤α/m}V = \sum_{i \in I_0}\mathbf 1\{p_i \le \alpha/m\}. By linearity of expectation, which needs no independence,

E[V]=∑i∈I0P(pi≤α/m)≤∑i∈I0αm=m0mα,E[V] = \sum_{i \in I_0}P(p_i \le \alpha/m) \le \sum_{i \in I_0}\frac{\alpha}{m} = \frac{m_0}{m}\alpha,

where the inequality is the validity of each null p-value at u=α/mu = \alpha/m. Since VV takes values in {0,1,2,… }\{0, 1, 2, \dots\}, 1{V≥1}≤V\mathbf 1\{V \ge 1\} \le V, and taking expectations gives P(V≥1)≤E[V]P(V \ge 1) \le E[V]. Finally m0≤mm_0 \le m. □\square

The first inequality is Markov's inequality at 1, and the whole chain is the union bound P(⋃i∈I0Ai)≤∑i∈I0P(Ai)P(\bigcup_{i \in I_0}A_i) \le \sum_{i \in I_0}P(A_i) with Ai={pi≤α/m}A_i = \{p_i \le \alpha/m\}. Because I0I_0 is arbitrary, the control is strong, not only under the global null I0={1,…,m}I_0 = \{1, \dots, m\}.

Theorem 2 (the bound is attained). Let m0=mm_0 = m and 0<α≤10 < \alpha \le 1. There is a joint law in which every pip_i is uniform on (0,1)(0, 1) and P(V≥1)=αP(V \ge 1) = \alpha exactly.

Proof. Let UU be uniform on (0,1)(0, 1) and pi=(U+i/m) mod 1p_i = (U + i/m) \bmod 1 for i=1,…,mi = 1, \dots, m. Each pip_i is a rotation of UU on the circle of length 1, so it is uniform. The event Ai={pi≤α/m}A_i = \{p_i \le \alpha/m\} is the event that UU lies in the arc [−i/m,−i/m+α/m][-i/m, -i/m + \alpha/m] taken modulo 1. These arcs have length α/m≤1/m\alpha/m \le 1/m and start at the mm distinct points −i/m-i/m, which are 1/m1/m apart, so they overlap at most at their end points, a set of probability zero. So P(⋃iAi)=∑iP(Ai)=m⋅α/m=αP(\bigcup_i A_i) = \sum_i P(A_i) = m \cdot \alpha/m = \alpha. □\square

So no procedure that uses the threshold c>α/mc > \alpha/m on every test can control the family-wise error rate at α\alpha under arbitrary dependence: on this law, it has error rate min⁡(1,mc)>α\min(1, mc) > \alpha. 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 NN values of UU with NN a multiple of mm, where each pip_i is uniform on {1/N,…,N/N}\{1/N, \dots, N/N\}.

Theorem 3 (Šidák under independence). If the null p-values are independent and uniform, and every HiH_i is tested at cS=1−(1−α)1/mc_S = 1 - (1 - \alpha)^{1/m}, then P(V≥1)=1−(1−α)m0/m≤αP(V \ge 1) = 1 - (1 - \alpha)^{m_0/m} \le \alpha, with equality when m0=mm_0 = m. Also cS≥α/mc_S \ge \alpha/m.

Proof. By independence, P(V=0)=∏i∈I0P(pi>cS)=(1−cS)m0=(1−α)m0/mP(V = 0) = \prod_{i \in I_0}P(p_i > c_S) = (1 - c_S)^{m_0} = (1 - \alpha)^{m_0/m}. This is at least 1−α1 - \alpha, with equality when m0=mm_0 = m. For the last claim, by Bernoulli's inequality (1−α/m)m≥1−α(1 - \alpha/m)^m \ge 1 - \alpha, so 1−α/m≥(1−α)1/m1 - \alpha/m \ge (1 - \alpha)^{1/m}, which is cS≥α/mc_S \ge \alpha/m. □\square

Under dependence Theorem 3 can fail. Šidák (1967) proved that for a normal vector with mean zero and any covariance, P(∣Xi∣≤ci for all i)≥∏iP(∣Xi∣≤ci)P(|X_i| \le c_i \text{ for all } i) \ge \prod_i P(|X_i| \le c_i), 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 mm 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 Θ(m)\Theta(m) in every case. The output takes Θ(m)\Theta(m) space; a streaming version that reads the p-values one at a time and reports each decision uses O(1)O(1) extra space, but it must know mm in advance.

Numerical stability. There is no cancellation. Compare pi≤α/mp_i \le \alpha/m or mpi≤αmp_i \le \alpha, never 1−pi≥1−α/m1 - p_i \ge 1 - \alpha/m, which loses all digits of a small pip_i. For the Šidák level, 1−(1−α)1/m1 - (1 - \alpha)^{1/m} cancels for large mm: with α=0.05\alpha = 0.05 and m=106m = 10^6, it is about 5.1×10−85.1 \times 10^{-8}, a difference of two numbers near 1. The implementation computes it as −expm1⁡(log1p⁡(−α)/m)-\operatorname{expm1}(\operatorname{log1p}(-\alpha)/m), 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 α\alpha, often far below. If all mm p-values are equal, it is α/m\alpha/m.
  • Nearly exact under independence for small α\alpha. With independent uniform nulls the error rate is 1−(1−α/m)m01 - (1 - \alpha/m)^{m_0}, which is between α−α2/2\alpha - \alpha^2/2 and α\alpha when m0=mm_0 = m.
  • Dominated by Holm. Holm's method rejects every hypothesis that Bonferroni rejects, with the same guarantee.
  • Controls the expected number of false rejections. E[V]≤(m0/m)αE[V] \le (m_0/m)\alpha, which bounds the per-family error rate as well.

Variants and improvements

  • Weighted Bonferroni. Give HiH_i the level wiαw_i\alpha with wi≥0w_i \ge 0 and ∑iwi≤1\sum_i w_i \le 1. 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 α\alpha on the false nulls.
  • Šidák correction. Test each hypothesis at 1−(1−α)1/m1 - (1 - \alpha)^{1/m}. With independent tests the family-wise error rate under the global null is exactly α\alpha. Š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 kk-th smallest with α/(m−k+1)\alpha/(m - k + 1). 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 α/m\alpha/m by a quantile of the minimum p-value under permutations, which adapts to the dependence.
  • Bonferroni confidence intervals. For mm parameters, use mm intervals at level 1−α/m1 - \alpha/m each. All mm cover at the same time with probability at least 1−α1 - \alpha. 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 mm 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. mm 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 pi≤α/mp_i \le \alpha/m", 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. mpimp_i 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 α/m\alpha/m is not "significant at α/m\alpha/m" 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.

bonferroni_correction.pyI0RawGitHub
# 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, P(⋃iAi)≤∑iP(Ai)P(\bigcup_i A_i) \le \sum_i P(A_i), 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 1−α/m1 - \alpha/m, 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 1−(1−α)1/m1 - (1 - \alpha)^{1/m}. Holm (1979) showed that a sequential use of the same inequality rejects more, with the same guarantee.

References

  1. 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
  2. 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)
  3. 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.

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