Algorithm Search⌘K

Algorithmintro

Sign test

Also called binomial sign test.

Tests a median, or paired differences, by the number of positive signs, which is Binomial(n, 1/2) under the null once zeros are dropped. Exact for every n and needs almost no assumptions.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the number of nonzero differences
Properties
deterministicexactofflineiterative
Origin
John Arbuthnot, W. J. Dixon, A. M. Mood, 1710

The sign test checks whether a median equals a given value μ0\mu_0, or whether paired differences are as likely to be positive as negative. It keeps only the sign of each observation. Under the null hypothesis each nonzero sign is a fair coin, so the number of positive signs SS has the exact law Binomial(n,1/2)\text{Binomial}(n, 1/2), and the test is a binomial test with p0=1/2p_0 = 1/2. It needs no normality and no symmetry, it is exact for every nn, and it is cheap. The price is power: it throws away the sizes of the differences, so when the data are close to normal the t-test and the Wilcoxon signed-rank test find a real effect with fewer observations.

In plain words

Ten patients try two sleeping drugs. For each patient, write a plus if the second drug gave more sleep and a minus if the first did. If the drugs are equally good, each sign is like a coin toss. Nine pluses out of nine (one patient had a tie and is left out) is very unlikely for a fair coin: the chance of a result this lopsided in either direction is 2 in 512. So the second drug looks better.

The test does not care whether the second drug gave 10 minutes or 5 hours more sleep. Only the direction counts. That makes it safe with strange data and outliers, but it also makes it slow to notice small effects.

The problem

Model. D1,…,DnD_1, \ldots, D_n are independent. In the paired design Di=Yi−XiD_i = Y_i - X_i is the difference within pair ii; in the one-sample design Di=Xi−μ0D_i = X_i - \mu_0. The DiD_i need not have the same distribution. Values Di=0D_i = 0 are dropped, and nn is the number of nonzero values that remain.

Hypotheses. H0H_0: P(Di>0)=P(Di<0)P(D_i > 0) = P(D_i < 0) for every ii. For identically distributed continuous data this says that μ0\mu_0 is a median of the distribution. The alternatives are "greater" (P(Di>0)>1/2P(D_i > 0) > 1/2), "less" (P(Di>0)<1/2P(D_i > 0) < 1/2) and two-sided.

Statistic. S=#{i:Di>0}S = \#\{i : D_i > 0\}, the number of positive signs.

Null distribution. Exact and conditional on the number of nonzero values: under H0H_0, given that Di≠0D_i \ne 0, the event Di>0D_i > 0 has probability 1/21/2, and the events are independent, so S∼Binomial(n,1/2)S \sim \text{Binomial}(n, 1/2).

P-values. Write b(k)=(nk)/2nb(k) = \binom{n}{k} / 2^n.

  • Greater: Phi(s)=∑k≥sb(k)P_{hi}(s) = \sum_{k \ge s} b(k).
  • Less: Plo(s)=∑k≤sb(k)P_{lo}(s) = \sum_{k \le s} b(k).
  • Two-sided: p(s)=min⁡{1,2min⁡(Plo(s),Phi(s))}p(s) = \min\{1, 2 \min(P_{lo}(s), P_{hi}(s))\}. The null law is symmetric about n/2n/2, so doubling gives the same value as the rule of the binomial test that sums the probabilities of all outcomes at most as likely as ss. The tests check this for every n≤29n \le 29.

Rejection rule and size. Reject at level α\alpha when p(s)≤αp(s) \le \alpha. The size is at most α\alpha for every nn, so the test is exact in the sense of valid, but conservative: the size equals α\alpha only when α\alpha is an attainable tail sum. For n=20n = 20 and α=0.05\alpha = 0.05 the two-sided test rejects for S≤5S \le 5 or S≥15S \ge 15, and its size is 2⋅0.020695=0.0413892 \cdot 0.020695 = 0.041389.

Sensitivity and power. The test detects any shift of P(D>0)P(D > 0) away from 1/21/2. Its power depends only on π=P(D>0∣D≠0)\pi = P(D > 0 \mid D \ne 0) and nn, through Binomial(n,π)\text{Binomial}(n, \pi). For D∼N(0.5,1)D \sim N(0.5, 1) and n=20n = 20, π=Φ(0.5)=0.6915\pi = \Phi(0.5) = 0.6915, and the exact two-sided power at α=0.05\alpha = 0.05 is 0.38420.3842.

The algorithm

  1. SIGN-TEST(d_1, ..., d_n, alternative)
  2. 1drop every d_i = 0, and let n be the number of values left
  3. 2S ← number of d_i > 0
  4. 3w[0] ← 1; w[k + 1] ← w[k] · (n - k) / (k + 1) for k = 0, ..., n - 1 ▷ w[k] = C(n, k), exact integers
  5. 4U ← w[S] + ... + w[n]; L ← w[0] + ... + w[S]
  6. 5if alternative = greater then return U / 2^n
  7. 6if alternative = less then return L / 2^n
  8. 7return min(1, 2 · min(U, L) / 2^n)

Lines L3 and L4 work with exact integers, and the code divides by 2n2^n only at the end. Python divides two integers with one correct rounding, so the float p-value is the exact rational rounded once, even when it is far below the smallest tail that 1−Plo1 - P_{lo} could show. The code also offers the normal approximation z=(∣S−n/2∣−1/2)/(n/2)z = (\lvert S - n/2 \rvert - 1/2) / (\sqrt{n}/2) with its continuity correction, and the distribution-free interval for the median described below.

Example

Paired data. The sleep data of Cushny and Peebles (1905), which Student (1908) used, give the extra hours of sleep of 10 patients under two drugs. The differences, drug 2 minus drug 1, are

1.2, 2.4, 1.3, 1.3, 0.0, 1.0, 1.8, 0.8, 4.6, 1.4.1.2,\ 2.4,\ 1.3,\ 1.3,\ 0.0,\ 1.0,\ 1.8,\ 0.8,\ 4.6,\ 1.4.

Line L1 drops the zero, so n=9n = 9. Line L2 gives S=9S = 9. Line L3 gives the row 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 of Pascal's triangle, and line L4 gives U=1U = 1 and L=512L = 512. The one-sided p-value is 1/512=0.001951/512 = 0.00195 and the two-sided p-value is 2/512=1/256=0.003912/512 = 1/256 = 0.00391. The normal approximation with the continuity correction gives 0.007660.00766, about twice the exact value; without the correction it gives 0.002700.00270. At n=9n = 9 neither approximation is good.

Mixed signs. For the differences 1.8,−0.6,3.1,2.4,−1.3,0.9,2.2,0.0,1.5,−0.41.8, -0.6, 3.1, 2.4, -1.3, 0.9, 2.2, 0.0, 1.5, -0.4, again n=9n = 9 after the zero is dropped, and S=6S = 6. Then L=1+9+36+84+126+126+84=466L = 1 + 9 + 36 + 84 + 126 + 126 + 84 = 466 and U=84+36+9+1=130U = 84 + 36 + 9 + 1 = 130, so the two-sided p-value is 260/512=65/128=0.508260/512 = 65/128 = 0.508. The signed-rank test on the same data gives 0.0740.074, because the three negative values are the small ones.

A small tail. With 900 positive signs out of 1000, the exact one-sided p-value is 6.70×10−1626.70 \times 10^{-162}. Computing it as 11 minus the sum of b(k)b(k) for k<900k < 900 in double precision gives exactly 00.

Correctness

The proof is in proofs/correctness.md. Under H0H_0, condition on the set of indices with Di≠0D_i \ne 0. Each such DiD_i is positive with probability 1/21/2, independently, so SS is Binomial(n,1/2)\text{Binomial}(n, 1/2) given nn. Lines L3 and L4 compute 2nPhi2^n P_{hi} and 2nPlo2^n P_{lo} exactly. Each p-value is a tail probability of an ordering of the outcomes, or twice the smaller of two such tails, so P(p≤α)≤αP(p \le \alpha) \le \alpha given nn, and therefore also without conditioning.

Proof: The sign test returns exact binomial tails, and each p-value is validfull

We use the pseudocode of the page. D1,…,DND_1, \ldots, D_N are independent, and under H0H_0 each satisfies P(Di>0)=P(Di<0)P(D_i > 0) = P(D_i < 0). Let Z={i:Di≠0}Z = \{i : D_i \ne 0\} be the random set of nonzero values and n=∣Z∣n = \lvert Z \rvert.

Claim 1 (the null law). Under H0H_0, conditional on Z=zZ = z with ∣z∣=n\lvert z \rvert = n, the statistic S=#{i∈z:Di>0}S = \#\{i \in z : D_i > 0\} is Binomial(n,1/2)\text{Binomial}(n, 1/2).

Proof. The events {Di>0}\{D_i > 0\} and {Di≠0}\{D_i \ne 0\} depend only on DiD_i, and the DiD_i are independent. Conditioning on Z=zZ = z is conditioning on {Di≠0}\{D_i \ne 0\} for i∈zi \in z and {Di=0}\{D_i = 0\} for i∉zi \notin z, so the indicators 1{Di>0}\mathbf{1}\{D_i > 0\}, i∈zi \in z, stay independent, and each has conditional probability P(Di>0)/(P(Di>0)+P(Di<0))=1/2P(D_i > 0) / (P(D_i > 0) + P(D_i < 0)) = 1/2. A sum of nn independent Bernoulli(1/2)(1/2) indicators is Binomial(n,1/2)\text{Binomial}(n, 1/2). □\square

Claim 2 (the returned values). Line L3 sets w[k]=(nk)w[k] = \binom{n}{k}: w[0]=1w[0] = 1, and (nk+1)=(nk)(n−k)/(k+1)\binom{n}{k + 1} = \binom{n}{k} (n - k)/(k + 1), where the division is exact because the result is an integer. Line L4 gives U=∑k≥S(nk)U = \sum_{k \ge S} \binom{n}{k} and L=∑k≤S(nk)L = \sum_{k \le S} \binom{n}{k}. So lines L5, L6 and L7 return Phi(S)=P(B≥S)P_{hi}(S) = P(B \ge S), Plo(S)=P(B≤S)P_{lo}(S) = P(B \le S) and min⁡{1,2min⁡(Plo,Phi)}\min\{1, 2 \min(P_{lo}, P_{hi})\} for B∼Binomial(n,1/2)B \sim \text{Binomial}(n, 1/2). □\square

Claim 3 (validity). For every α∈[0,1]\alpha \in [0, 1], PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha for each of the three p-values.

Proof. Condition on Z=zZ = z; by Claim 1, S∼BS \sim B. For the "greater" p-value, let A={s:P(B≥s)≤α}A = \{s : P(B \ge s) \le \alpha\}. If AA is empty the probability is 00. Otherwise let s∗s^* be its smallest element. Every s∈As \in A has s≥s∗s \ge s^*, so P(S∈A)≤P(B≥s∗)≤αP(S \in A) \le P(B \ge s^*) \le \alpha. The "less" case is the same with the order reversed. For the two-sided p-value, p≤αp \le \alpha forces Phi(S)≤α/2P_{hi}(S) \le \alpha/2 or Plo(S)≤α/2P_{lo}(S) \le \alpha/2, and each event has conditional probability at most α/2\alpha/2 by the one-sided argument. So the conditional probability of rejection is at most α\alpha for every zz, and averaging over ZZ gives the unconditional bound. □\square

Claim 4 (the two-sided rule). Doubling equals the rule that sums the null probabilities of all outcomes at most as likely as SS.

Proof. b(k)=(nk)/2nb(k) = \binom{n}{k}/2^n is symmetric, b(k)=b(n−k)b(k) = b(n - k), and increases for k≤n/2k \le n/2. Take s≤n/2s \le n/2 (the other case is symmetric). The outcomes kk with b(k)≤b(s)b(k) \le b(s) are k≤sk \le s and k≥n−sk \ge n - s. If s<n/2s < n/2 these sets are disjoint and their probability is 2P(B≤s)=2min⁡(Plo,Phi)2 P(B \le s) = 2 \min(P_{lo}, P_{hi}). If s=n/2s = n/2 every outcome qualifies, the sum is 11, and 2P(B≤s)≥12 P(B \le s) \ge 1, so the minimum with 11 gives 11 as well. □\square

Cost. Lines L1 and L2 take one pass. Line L3 does nn multiplications and exact divisions, and line L4 at most 2n+22n + 2 additions. In the real-RAM model with unit-cost arithmetic the time is Θ(n)\Theta(n) and the list takes Θ(n)\Theta(n) space. □\square

Complexity

Line L1 and line L2 scan the data once. Line L3 does nn multiplications and divisions and line L4 does at most 2n2n additions, so the time is Θ(n)\Theta(n) arithmetic operations and the list ww takes Θ(n)\Theta(n) space. The integers have up to nn bits, so counted in bit operations lines L3 and L4 cost Θ(n2)\Theta(n^2). With the regularized incomplete beta function, Phi(s)=I1/2(s,n−s+1)P_{hi}(s) = I_{1/2}(s, n - s + 1) costs much less for large nn, at the price of floating-point error.

Properties

  • Distribution-free. The null law does not depend on the distribution of the DiD_i, and the DiD_i may even have different distributions, as long as each has median μ0\mu_0 and no mass there.
  • Conservative. The size is at most α\alpha; for n=20n = 20 and α=0.05\alpha = 0.05 it is 0.04140.0414.
  • Robust. One wild value changes SS by at most 1.
  • Power. For D∼N(θ,1)D \sim N(\theta, 1), the asymptotic relative efficiency of the sign test against the t-test is 2/π≈0.6372/\pi \approx 0.637; for the Laplace (double exponential) law it is 22, and the sign test is then the better test (Lehmann 2006). At n=20n = 20 and D∼N(0.5,1)D \sim N(0.5, 1), the exact power is 0.3840.384. A Monte Carlo run with r=2000r = 2000 samples and seed 12 gave power 0.3870.387 for the sign test and 0.5400.540 for the signed-rank test on the same samples.
  • Validity without symmetry. A Monte Carlo run with n=20n = 20, r=2000r = 2000 samples of D=E−ln⁡2D = E - \ln 2, EE exponential with mean 1 (median 0, skewed), and seed 11 rejected at α=0.05\alpha = 0.05 in 3.9%3.9\% of samples. The signed-rank test rejected in 10.1%10.1\%, because it tests symmetry, not the median.

Variants and improvements

  • Interval for the median. Inverting the test gives the interval [X(k),X(n+1−k)][X_{(k)}, X_{(n + 1 - k)}] between two order statistics, where kk is the largest index with 2P(Binomial(n,1/2)≤k−1)≤α2 P(\text{Binomial}(n, 1/2) \le k - 1) \le \alpha. Its coverage is exactly 1−2P(Binomial(n,1/2)≤k−1)1 - 2 P(\text{Binomial}(n, 1/2) \le k - 1) for every continuous distribution. For n=20n = 20 and α=0.05\alpha = 0.05, k=6k = 6 and the coverage is 0.95860.9586. For the 10 sleep differences, k=2k = 2, the interval is [0.8,2.4][0.8, 2.4] and its coverage is 501/512=0.9785501/512 = 0.9785. This is an example of test-interval duality.
  • Normal approximation. z=(S−n/2)/(n/2)z = (S - n/2)/(\sqrt{n}/2), with the continuity correction of 1/21/2 toward n/2n/2. It is fine for large nn but has no advantage over the exact sum.
  • Ties at μ0\mu_0. Dropping the zeros is the usual rule and keeps the test exact given the number of zeros. Two other rules count each zero as half a success, or assign the zeros a sign at random. Both change the null law, and neither is used by the code.
  • Mid-p and randomized tests. As for the binomial test, the mid-p value reduces the conservatism at the cost of an exact size bound.
  • McNemar's test. On a paired 2×22 \times 2 table, the exact McNemar test is the sign test applied to the discordant pairs.
  • Signed ranks. The Wilcoxon signed-rank test also uses the sizes of the differences, through their ranks. It is more powerful near the normal but needs symmetry.

When to use it

Use it when only the direction of each difference is reliable (ratings, before and after preferences), when the data have heavy tails or outliers, or when the question is about the median and the distribution may be skewed. For differences that are close to normal, the paired t-test or the signed-rank test needs fewer pairs for the same power. The sign test is also a good first check, because it can be done by hand.

Pitfalls

  • Zeros. Count nn after dropping the zeros. Using the full sample size with the zeros counted as negative makes the test biased.
  • The normal approximation at small nn. For the sleep data at n=9n = 9 the approximation with the continuity correction gave 0.00770.0077 against the exact 0.00390.0039. Compute the exact value; it costs nothing.
  • Small p-values. Sum the upper tail directly, or in exact integers as line L4 does. 1−P(S<s)1 - P(S < s) in double precision returned 00 for a p-value of 6.7×10−1626.7 \times 10^{-162}.
  • Dependent pairs. The test needs the signs to be independent. Repeated measures on the same subject, or a time series, break this.
  • Not a test of the mean. For a skewed distribution the median and the mean differ, and the sign test says nothing about the mean.

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.

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

import math
from fractions import Fraction

ALTERNATIVES = ("two-sided", "greater", "less")


def sign_counts(d: list[float], mu0: float = 0.0) -> tuple[int, int]:
    """Return (s, n): the number of d_i - mu0 > 0 and the number of nonzero d_i - mu0."""
    kept = [v - mu0 for v in d if v != mu0]
    return sum(1 for v in kept if v > 0), len(kept)


def sign_test(
    d: list[float], alternative: str = "two-sided", mu0: float = 0.0, exact: bool = False
) -> float | Fraction:
    """Exact p-value of the sign test of H0: P(D > mu0) = P(D < mu0).

    d holds the paired differences, or the sample itself for a test of the
    median mu0. Values equal to mu0 are dropped. "greater" is the alternative
    P(D > mu0) > 1/2, "less" the alternative P(D > mu0) < 1/2. The two-sided
    p-value doubles the smaller tail, which is the same as the rule that sums
    all outcomes at most as likely as the observed one, because the null law
    Binomial(n, 1/2) is symmetric. The tails are exact integer sums divided by
    2^n; exact=True returns the Fraction, otherwise the correctly rounded float.
    """
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    kept = [v - mu0 for v in d if v != mu0]  # @line L1
    s, n = sum(1 for v in kept if v > 0), len(kept)  # @line L2
    w = [1] * (n + 1)  # @line L3
    for k in range(n):
        w[k + 1] = w[k] * (n - k) // (k + 1)  # w[k] = C(n, k), exact integers
    upper, lower = sum(w[s:]), sum(w[: s + 1])  # @line L4
    total = 2**n
    if alternative == "greater":  # @line L5
        p = Fraction(upper, total)
    elif alternative == "less":  # @line L6
        p = Fraction(lower, total)
    else:
        p = min(Fraction(1), Fraction(2 * min(upper, lower), total))  # @line L7
    return p if exact else float(p)


def sign_test_normal(
    d: list[float], alternative: str = "two-sided", mu0: float = 0.0, correction: bool = True
) -> float:
    """Normal approximation to the sign test, with an optional continuity correction of 1/2."""
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    s, n = sign_counts(d, mu0)
    if n == 0:
        return 1.0
    c = 0.5 if correction else 0.0
    sd = math.sqrt(n) / 2.0
    if alternative == "greater":
        z = (s - n / 2.0 - c) / sd
        return 0.5 * math.erfc(z / math.sqrt(2.0))
    if alternative == "less":
        z = (s - n / 2.0 + c) / sd
        return 0.5 * math.erfc(-z / math.sqrt(2.0))
    z = max(0.0, abs(s - n / 2.0) - c) / sd
    return min(1.0, math.erfc(z / math.sqrt(2.0)))


def median_interval(x: list[float], alpha: float) -> tuple[float, float, Fraction]:
    """Distribution-free interval [x_(k), x_(n+1-k)] for the median, from the sign test.

    k is the largest index with 2 P(Binomial(n, 1/2) <= k - 1) <= alpha. Returns
    the two ends and the exact coverage 1 - 2 P(Binomial(n, 1/2) <= k - 1) for a
    continuous distribution. Raises ValueError if n is too small for alpha.
    """
    n = len(x)
    xs = sorted(x)
    k, tail = 0, 0
    while 2 * (tail + math.comb(n, k)) <= alpha * 2**n:
        tail += math.comb(n, k)
        k += 1
    if k == 0:
        raise ValueError("n is too small for this alpha")
    return xs[k - 1], xs[n - k], 1 - Fraction(2 * tail, 2**n)
sign_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sign-test/. The authors are listed in prov/R4JDYX.jsonl.
"""Entry point named after the slug. The code lives in sign_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from sign_core import ALTERNATIVES, median_interval, sign_counts, sign_test, sign_test_normal

__all__ = ["ALTERNATIVES", "median_interval", "sign_counts", "sign_test", "sign_test_normal"]
test_sign_test.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sign-test/. The authors are listed in prov/R4JDYX.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from sign_test import median_interval, sign_counts, sign_test, sign_test_normal

# Cushny and Peebles (1905), as used by Student (1908): extra hours of sleep under two drugs.
DRUG_1 = [0.7, -1.6, -0.2, -1.2, -0.1, 3.4, 3.7, 0.8, 0.0, 2.0]
DRUG_2 = [1.9, 0.8, 1.1, 0.1, -0.1, 4.4, 5.5, 1.6, 4.6, 3.4]
DIFF = [round(b - a, 1) for a, b in zip(DRUG_1, DRUG_2)]


def brute_force(signs_observed: int, n: int) -> tuple[Fraction, Fraction]:
    """Upper and lower tails by listing all 2^n equally likely sign vectors."""
    upper = lower = 0
    for signs in itertools.product((0, 1), repeat=n):
        s = sum(signs)
        upper += s >= signs_observed
        lower += s <= signs_observed
    return Fraction(upper, 2**n), Fraction(lower, 2**n)


def test_sleep_example() -> None:
    assert sign_counts(DIFF) == (9, 9)
    assert sign_test(DIFF, exact=True) == Fraction(1, 256)
    assert sign_test(DIFF, "greater", exact=True) == Fraction(1, 512)
    assert sign_test(DIFF, "less", exact=True) == 1
    assert sign_test_normal(DIFF) == pytest.approx(0.0076607611, abs=1e-9)


def test_against_all_sign_vectors() -> None:
    for n in range(0, 13):
        for s in range(n + 1):
            d = [1.0] * s + [-1.0] * (n - s) + [0.0, 0.0]
            upper, lower = brute_force(s, n)
            assert sign_test(d, "greater", exact=True) == upper
            assert sign_test(d, "less", exact=True) == lower
            assert sign_test(d, exact=True) == min(Fraction(1), 2 * min(upper, lower))
            assert sign_test(d) == float(min(Fraction(1), 2 * min(upper, lower)))


def test_two_sided_equals_min_likelihood_rule() -> None:
    for n in range(1, 30):
        pmf = [Fraction(math.comb(n, k), 2**n) for k in range(n + 1)]
        for s in range(n + 1):
            d = [1.0] * s + [-1.0] * (n - s)
            ml = sum(v for v in pmf if v <= pmf[s])
            assert sign_test(d, exact=True) == ml


def test_size_never_exceeds_alpha() -> None:
    for n in (1, 5, 10, 17, 30):
        pmf = [Fraction(math.comb(n, k), 2**n) for k in range(n + 1)]
        for alpha in (Fraction(1, 100), Fraction(1, 20), Fraction(1, 10)):
            for alt in ("greater", "less", "two-sided"):
                size = sum(pmf[s] for s in range(n + 1)
                           if sign_test([1.0] * s + [-1.0] * (n - s), alt, exact=True) <= alpha)
                assert size <= alpha


def test_size_monte_carlo_with_zero_median() -> None:
    # Data from a skewed law with median 0: the sign test keeps its level.
    rng = random.Random(7)
    n, r, alpha = 20, 2000, 0.05
    rejections = 0
    for _ in range(r):
        d = [rng.expovariate(1.0) - math.log(2.0) for _ in range(n)]
        rejections += sign_test(d) <= alpha
    rate = rejections / r
    assert rate <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_small_tail_keeps_digits() -> None:
    d = [1.0] * 900 + [-1.0] * 100
    want = Fraction(sum(math.comb(1000, k) for k in range(900, 1001)), 2**1000)
    assert sign_test(d, "greater") == pytest.approx(float(want), rel=1e-12)
    assert sign_test(d, "greater") < 1e-150


def test_mu0_shift_and_zeros() -> None:
    x = [1.2, 3.4, 2.0, 2.0, 5.1, 0.3, 2.7]
    assert sign_counts(x, mu0=2.0) == (3, 5)
    assert sign_test(x, mu0=2.0, exact=True) == 1
    assert sign_test([0.0, 0.0], exact=True) == 1


def test_median_interval() -> None:
    x = list(range(1, 21))
    lo, hi, cover = median_interval([float(v) for v in x], 0.05)
    assert (lo, hi) == (6.0, 15.0)
    assert cover == 1 - Fraction(2 * sum(math.comb(20, j) for j in range(6)), 2**20)
    assert cover >= Fraction(95, 100)
    with pytest.raises(ValueError):
        median_interval([1.0, 2.0, 3.0], 0.05)


def test_bad_alternative() -> None:
    with pytest.raises(ValueError):
        sign_test([1.0], "both")

History

John Arbuthnot (1710) observed that in each of the 82 years from 1629 to 1710 more boys than girls were christened in London. Under even chances this has probability (1/2)82(1/2)^{82}, so his argument is a one-sided sign test with n=82n = 82 and S=82S = 82, and it is often called the first published significance test. The test was used informally for two centuries. Dixon and Mood (1946) brought the earlier results together in one paper with a table of significance levels and worked examples, and noted that tests such as the t-test are more efficient when the sizes of the differences can be trusted. Hollander, Wolfe and Chicken name it the Fisher sign test.

References

  1. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 3 (the one-sample location problem), Section 3.4 (the Fisher sign test and the estimators and interval that come from it)
  2. E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on paired comparisons and the one-sample problem (the sign test and its efficiency against the t-test)
  3. W. J. Dixon and A. M. Mood, The statistical sign test, Journal of the American Statistical Association 41(236), 1946, pp. 557 to 566 (a summary of earlier results, a table of significance levels and worked examples)
  4. John Arbuthnot, An argument for Divine Providence, taken from the constant regularity observed in the births of both sexes, Philosophical Transactions of the Royal Society 27, 1710, pp. 186 to 190 (82 years of christenings, each with more males than females)

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