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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John Arbuthnot, W. J. Dixon, A. M. Mood, 1710
The sign test checks whether a median equals a given value , 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 has the exact law , and the test is a binomial test with . It needs no normality and no symmetry, it is exact for every , 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. are independent. In the paired design is the difference within pair ; in the one-sample design . The need not have the same distribution. Values are dropped, and is the number of nonzero values that remain.
Hypotheses. : for every . For identically distributed continuous data this says that is a median of the distribution. The alternatives are "greater" (), "less" () and two-sided.
Statistic. , the number of positive signs.
Null distribution. Exact and conditional on the number of nonzero values: under , given that , the event has probability , and the events are independent, so .
P-values. Write .
- Greater: .
- Less: .
- Two-sided: . The null law is symmetric about , 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 . The tests check this for every .
Rejection rule and size. Reject at level when . The size is at most for every , so the test is exact in the sense of valid, but conservative: the size equals only when is an attainable tail sum. For and the two-sided test rejects for or , and its size is .
Sensitivity and power. The test detects any shift of away from . Its power depends only on and , through . For and , , and the exact two-sided power at is .
The algorithm
SIGN-TEST(d_1, ..., d_n, alternative)- 1
drop every d_i = 0, and let n be the number of values left - 2
S ← number of d_i > 0 - 3
w[0] ← 1; w[k + 1] ← w[k] · (n - k) / (k + 1) for k = 0, ..., n - 1 ▷ w[k] = C(n, k), exact integers - 4
U ← w[S] + ... + w[n]; L ← w[0] + ... + w[S] - 5
if alternative = greater then return U / 2^n - 6
if alternative = less then return L / 2^n - 7
return min(1, 2 · min(U, L) / 2^n)
Lines L3 and L4 work with exact integers, and the code divides by 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 could show. The code also offers the normal approximation 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
Line L1 drops the zero, so . Line L2 gives . Line L3 gives the row 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 of Pascal's triangle, and line L4 gives and . The one-sided p-value is and the two-sided p-value is . The normal approximation with the continuity correction gives , about twice the exact value; without the correction it gives . At neither approximation is good.
Mixed signs. For the differences , again after the zero is dropped, and . Then and , so the two-sided p-value is . The signed-rank test on the same data gives , 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 . Computing it as minus the sum of for in double precision gives exactly .
Correctness
The proof is in proofs/correctness.md. Under , condition on the set of indices with . Each such is positive with probability , independently, so is given . Lines L3 and L4 compute and exactly. Each p-value is a tail probability of an ordering of the outcomes, or twice the smaller of two such tails, so given , 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. are independent, and under each satisfies . Let be the random set of nonzero values and .
Claim 1 (the null law). Under , conditional on with , the statistic is .
Proof. The events and depend only on , and the are independent. Conditioning on is conditioning on for and for , so the indicators , , stay independent, and each has conditional probability . A sum of independent Bernoulli indicators is .
Claim 2 (the returned values). Line L3 sets : , and , where the division is exact because the result is an integer. Line L4 gives and . So lines L5, L6 and L7 return , and for .
Claim 3 (validity). For every , for each of the three p-values.
Proof. Condition on ; by Claim 1, . For the "greater" p-value, let . If is empty the probability is . Otherwise let be its smallest element. Every has , so . The "less" case is the same with the order reversed. For the two-sided p-value, forces or , and each event has conditional probability at most by the one-sided argument. So the conditional probability of rejection is at most for every , and averaging over gives the unconditional bound.
Claim 4 (the two-sided rule). Doubling equals the rule that sums the null probabilities of all outcomes at most as likely as .
Proof. is symmetric, , and increases for . Take (the other case is symmetric). The outcomes with are and . If these sets are disjoint and their probability is . If every outcome qualifies, the sum is , and , so the minimum with gives as well.
Cost. Lines L1 and L2 take one pass. Line L3 does multiplications and exact divisions, and line L4 at most additions. In the real-RAM model with unit-cost arithmetic the time is and the list takes space.
Complexity
Line L1 and line L2 scan the data once. Line L3 does multiplications and divisions and line L4 does at most additions, so the time is arithmetic operations and the list takes space. The integers have up to bits, so counted in bit operations lines L3 and L4 cost . With the regularized incomplete beta function, costs much less for large , at the price of floating-point error.
Properties
- Distribution-free. The null law does not depend on the distribution of the , and the may even have different distributions, as long as each has median and no mass there.
- Conservative. The size is at most ; for and it is .
- Robust. One wild value changes by at most 1.
- Power. For , the asymptotic relative efficiency of the sign test against the t-test is ; for the Laplace (double exponential) law it is , and the sign test is then the better test (Lehmann 2006). At and , the exact power is . A Monte Carlo run with samples and seed 12 gave power for the sign test and for the signed-rank test on the same samples.
- Validity without symmetry. A Monte Carlo run with , samples of , exponential with mean 1 (median 0, skewed), and seed 11 rejected at in of samples. The signed-rank test rejected in , because it tests symmetry, not the median.
Variants and improvements
- Interval for the median. Inverting the test gives the interval between two order statistics, where is the largest index with . Its coverage is exactly for every continuous distribution. For and , and the coverage is . For the 10 sleep differences, , the interval is and its coverage is . This is an example of test-interval duality.
- Normal approximation. , with the continuity correction of toward . It is fine for large but has no advantage over the exact sum.
- Ties at . 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 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 after dropping the zeros. Using the full sample size with the zeros counted as negative makes the test biased.
- The normal approximation at small . For the sleep data at the approximation with the continuity correction gave against the exact . Compute the exact value; it costs nothing.
- Small p-values. Sum the upper tail directly, or in exact integers as line L4 does. in double precision returned for a p-value of .
- 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.
# 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 , so his argument is a one-sided sign test with and , 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
- 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)
- 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)
- 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)
- 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.
| 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 R4JDYX Edit this page History Report an error Markdown