Algorithmcore
Wilcoxon signed-rank test
Also called signed-rank test.
Tests whether paired differences are symmetric about zero by the sum of the ranks of their absolute values that belong to positive differences.
- Time
- Θ(n^3) worst · best
- Space
- Θ(n^2) extra
- Where
- n = the number of nonzero differences
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frank Wilcoxon, 1945
The Wilcoxon signed-rank test checks whether paired differences are symmetric about zero, or about a given value . It ranks the absolute differences and adds the ranks of the positive ones. Under the null hypothesis each sign is a fair coin given the absolute values, so the sum has an exact law that depends only on the ranks, and a short dynamic program counts it. Unlike the sign test, it uses the sizes of the differences through their ranks, so it is nearly as powerful as the paired t-test for normal data and much better for heavy tails. The price is the extra assumption of symmetry: it is not a test of the median alone.
In plain words
Ten patients try two drugs, and for each one we note how much more the second drug helped. Put the differences in order of size, ignoring the sign, and number them 1, 2, 3 and so on. Then add up the numbers that belong to differences where the second drug was better.
If the drugs are equally good and the differences are spread evenly around zero, each number is equally likely to land on the plus side or the minus side, like a coin toss. So the sum is usually near half the total. A sum close to the total means the large differences all point the same way, which is hard to explain by luck. Small differences count little and large ones count much, so one big outlier counts only as the largest rank, not as its full size.
The problem
Model. are independent. In the paired design ; in the one-sample design . Values are dropped, and is the number of nonzero values left.
Hypotheses. : each has a distribution symmetric about , that is, and have the same law. The may have different symmetric laws. The alternatives are "greater" (the tend to be positive), "less" and two-sided. A shift model , with symmetric about 0, is the usual setting, and then is .
Statistic. Rank from to , giving tied values the mean of their ranks (midranks). Then .
Null distribution. Exact and conditional on the absolute values. Under , given , the signs are independent fair coins, so has the law of with independent , . Each of the sign vectors has probability . The mean is and the variance is , where are the sizes of the groups of tied . The law is symmetric about its mean.
P-values. With the number of sign vectors whose sum is :
- Greater: .
- Less: .
- Two-sided: . The null law is symmetric about its mean, so doubling equals .
Rejection rule and size. Reject at level when . The size is at most for every , and with ties it is at most conditionally on the tie pattern. The null law is discrete, so the size is usually below . For without ties the two-sided test at rejects for or , with size .
Sensitivity and power. The test detects a shift of a symmetric law. It also reacts to asymmetry: a skewed law with median is outside , and the test rejects it often (see Properties). In the shift model its asymptotic relative efficiency against the t-test is under normal errors, and at least for every symmetric continuous law (Hodges and Lehmann 1956).
The algorithm
SIGNED-RANK-TEST(d_1, ..., d_n, alternative)- 1
drop every d_i = 0, and let n be the number of values left - 2
r_i ← 2 · (midrank of |d_i| among |d_1|, ..., |d_n|) ▷ doubled, so every r_i is an integer - 3
w ← sum of r_i over the i with d_i > 0 - 4
T ← r_1 + ... + r_n; c[0] ← 1; c[s] ← 0 for s = 1, ..., T - 5
for i ← 1 to n - 6
for s ← T down to r_i: c[s] ← c[s] + c[s - r_i] ▷ c[s] counts subsets with sum s - 7
U ← c[w] + ... + c[T]; L ← c[0] + ... + c[w] - 8
return U / 2^n, L / 2^n or min(1, 2 · min(U, L) / 2^n) for greater, less or two-sided
The code returns and the p-value. Lines L5 and L6 are the standard count of subsets by their sum; the downward loop in line L6 uses each at most once. Midranks of tied values can be half-integers, so the code doubles every rank and counts doubled sums; then all indices are integers and every count is exact. The division by in line L8 is one exact rational, rounded once to a float. The code also offers the normal approximation with the tie-corrected variance given above.
Example
Mixed signs. Take the differences . Line L1 drops the zero, so . The absolute values in order are , with ranks 1 to 9. The negative differences have ranks 1, 2 and 4, so . A value means the negative ranks sum to at most 7, and 19 of the 512 subsets of have a sum of at most 7. So the one-sided p-value is and the two-sided p-value is . The normal approximation gives and with the continuity correction, and and without it. The sign test on the same data gives , because it ignores that the three negative values are among the four smallest.
The counts. For without ties the doubled ranks are , and lines L5 and L6 give the counts of as , which add up to . With ranks (a tie in the middle) the doubled ranks are , and the nonzero counts are at the doubled sums , with counts . Both lists are symmetric, as the proof requires.
Paired data. For the sleep data of Cushny and Peebles (1905) the 9 nonzero differences are all positive, so , the largest value, and the two-sided p-value is , the same as for the sign test. The normal approximation gives with the continuity correction and without it.
Correctness
The proof is in proofs/correctness.md. Given the absolute values, symmetry of each makes its sign a fair coin independent of everything else, and the ranks are fixed by the absolute values. So the conditional null law of gives each of the subsets of ranks the probability . After step of line L5, is the number of subsets of with sum , because a subset either leaves out (the old ) or contains it (the old ). Line L7 then gives exact tail counts, and each p-value is valid by the argument used for the sign test.
Proof: The signed-rank test computes the exact conditional null law, and each p-value is validfull
We use the pseudocode of the page. are independent, and under each has the same law as . Let , , and .
Claim 1 (the signs given the sizes). Under , conditional on and , the signs , , are independent and each equals 1 with probability .
Proof. Write with . Symmetry gives , so for every Borel set , . Hence, given and , is with probability each. The pairs are independent over , so these conditional laws are independent.
Claim 2 (the null law). Let be the doubled midranks of , which line L2 computes and which depend only on . Conditional on and , , and each of the vectors has probability . So , where is the number of subsets of the multiset (subsets of indices) with sum .
Proof. Immediate from Claim 1, because the ranks are functions of .
Claim 3 (the dynamic program). After the iteration of line L5, is the number of index sets with , for every .
Proof. Induction on . Before the loop, (the empty set) and for . In iteration , a set with sum either leaves out , and is counted by the old , or contains , and then has sum and is counted by the old . Line L6 visits in decreasing order, so when it reads with , that entry has not yet been updated in this iteration and still holds the old value. Entries with are not changed, which is correct because no set containing has such a sum.
Claim 4 (the returned values). Line L3 gives . By Claims 2 and 3, line L7 gives and , and line L8 returns the three p-values of the page exactly.
Claim 5 (validity). For every , for each p-value.
Proof. Condition on and , so that the null law of is the discrete law of Claim 2. For the "greater" p-value, the set is empty or has a least element , and the conditional probability of rejection is . The "less" case is the same in the other direction. For the two-sided p-value, rejection forces one of the two one-sided p-values to be at most , and each event has conditional probability at most . Averaging over keeps the bound.
Claim 6 (symmetry and the two-sided rule). , so the conditional law of is symmetric about , and , capped at 1, equals .
Proof. Taking complements, , is a bijection from the sets with sum to the sets with sum . Take ; the other case is symmetric. The event is the union of and , which by symmetry have the same probability . If the two events are disjoint and the union has probability ; also there. If the event is certain, and , so the cap gives 1.
Moments. Given , with , so , because midranks keep the sum . . A tie group of size that covers the ranks has midrank , and replacing the ranks by lowers the sum of squares by . So . The tests check both formulas in exact fractions.
Cost. Line L2 sorts in . , so line L6 does at most additions for each of the values of : additions in total, and the array has entries. Line L7 costs .
Complexity
Lines L1 to L3 cost for the sort. The total of the doubled ranks is , so line L6 runs times for each of the values of , and lines L5 and L6 cost additions. The array has entries, so the space is . The counts are integers below , so in bit operations the cost is . For in the hundreds the normal approximation is accurate and costs .
Properties
- Distribution-free under symmetry. The conditional null law depends only on the tie pattern, not on the law of the .
- Conservative and exact. The size is at most , and the p-values are exact rationals.
- Robust. A wild value enters only through its rank, which is at most , however large the value is.
- Efficiency. In the shift model the efficiency against the t-test is for normal errors and at least for every symmetric law; for heavy tails it can be arbitrarily large. A Monte Carlo run with , , samples and seed 12 gave power at , against for the sign test on the same samples.
- Symmetry matters. A Monte Carlo run with , samples of , exponential with mean 1 (median 0 but skewed), and seed 11 rejected at in of samples. The sign test rejected in . The signed-rank test is a test of symmetry about , not of the median.
Variants and improvements
- Estimator and interval. The Hodges-Lehmann estimator of the center is the median of the Walsh averages , . Inverting the test gives a confidence interval between two order statistics of the Walsh averages, an example of test-interval duality.
- Zeros. Dropping the zeros is Wilcoxon's rule and the one the code uses. Pratt (1959) proposed ranking the zeros with the other values and then dropping them from the sum, which changes the null law.
- Normal approximation. with the tie-corrected variance and a continuity correction of . For it gave against the exact .
- Paired permutation test. Using the differences themselves in place of their ranks gives the permutation test over sign changes. It is exact under the same hypothesis, but its null law depends on the data, so it cannot be tabulated.
- More than two conditions. For blocks with more than two treatments, the Friedman test ranks within each block.
When to use it
Use it for paired data or for one sample about a point, when the differences are plausibly symmetric but maybe not normal: measurement errors, before and after scores on an interval scale, differences of logarithms. It loses little against the t-test for normal data and wins for heavy tails. If the distribution of the differences may be skewed and the question is about the median, use the sign test. If only the direction of each difference is reliable, the ranks of the sizes mean nothing, and the sign test is again the right choice.
Pitfalls
- It is not a median test. For skewed differences with median 0 it rejected in of Monte Carlo samples at the nominal .
- Ranks need meaningful differences. Ranking assumes that differences can be compared across pairs. For ordinal ratings this may be false.
- Ties and the normal approximation. Without the tie correction to the variance, the approximation is conservative. The exact count in lines L5 and L6 handles ties with no approximation.
- Large . The exact count costs time and space; for in the thousands use the normal approximation.
- Two different "Wilcoxon tests". The signed-rank test is for paired data. For two independent samples, use the rank-sum test, which is the Mann-Whitney U test.
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/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.
import math
from fractions import Fraction
ALTERNATIVES = ("two-sided", "greater", "less")
def doubled_midranks(values: list[float]) -> list[int]:
"""Return 2 x (midrank of each value), in input order. Doubling keeps midranks integers."""
n = len(values)
order = sorted(range(n), key=values.__getitem__)
r2 = [0] * n
i = 0
while i < n:
j = i
while j + 1 < n and values[order[j + 1]] == values[order[i]]:
j += 1
for t in range(i, j + 1):
r2[order[t]] = i + j + 2 # 2 x the mean of the ranks i + 1, ..., j + 1
i = j + 1
return r2
def tie_sizes(values: list[float]) -> list[int]:
"""Sizes of the groups of equal values."""
counts: dict[float, int] = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
return list(counts.values())
def signed_rank_counts(r2: list[int]) -> list[int]:
"""c[s] = number of subsets of the doubled ranks r2 with sum s (a subset-sum count)."""
total = sum(r2)
c = [0] * (total + 1)
c[0] = 1
for r in r2: # @line L5
for s in range(total, r - 1, -1): # @line L6
c[s] += c[s - r]
return c
def wilcoxon_signed_rank(
d: list[float], alternative: str = "two-sided", mu0: float = 0.0, exact: bool = False
) -> tuple[float, float | Fraction]:
"""Wilcoxon signed-rank test of H0: D - mu0 is symmetric about 0.
Returns (W+, p). Differences equal to mu0 are dropped. Tied |d_i| get
midranks, and the null law is then the exact conditional law given the
ranks: the signs are independent fair coins. "greater" is the alternative
that D tends to exceed mu0. The two-sided p-value doubles the smaller tail;
the null law is symmetric, so this equals P(|W+ - E W+| >= |w - E W+|).
"""
if alternative not in ALTERNATIVES:
raise ValueError("unknown alternative")
kept = [v - mu0 for v in d if v != mu0] # @line L1
n = len(kept)
r2 = doubled_midranks([abs(v) for v in kept]) # @line L2
w2 = sum(r for r, v in zip(r2, kept) if v > 0) # @line L3
c = signed_rank_counts(r2) # @line L4
upper = sum(c[w2:]) # @line L7
lower = sum(c[: w2 + 1])
total = 2**n
if alternative == "greater": # @line L8
p = Fraction(upper, total)
elif alternative == "less":
p = Fraction(lower, total)
else:
p = min(Fraction(1), Fraction(2 * min(upper, lower), total))
return w2 / 2, (p if exact else float(p))
def wilcoxon_normal(
d: list[float], alternative: str = "two-sided", mu0: float = 0.0, correction: bool = True
) -> tuple[float, float]:
"""Normal approximation with the tie-corrected variance. Returns (z, p)."""
if alternative not in ALTERNATIVES:
raise ValueError("unknown alternative")
kept = [v - mu0 for v in d if v != mu0]
n = len(kept)
if n == 0:
return 0.0, 1.0
a = [abs(v) for v in kept]
w = sum(r for r, v in zip(doubled_midranks(a), kept) if v > 0) / 2
mean = n * (n + 1) / 4
var = n * (n + 1) * (2 * n + 1) / 24 - sum(t**3 - t for t in tie_sizes(a)) / 48
sd = math.sqrt(var)
c = 0.5 if correction else 0.0
if alternative == "greater":
z = (w - mean - c) / sd
return z, 0.5 * math.erfc(z / math.sqrt(2.0))
if alternative == "less":
z = (w - mean + c) / sd
return z, 0.5 * math.erfc(-z / math.sqrt(2.0))
z = math.copysign(max(0.0, abs(w - mean) - c), w - mean) / sd
return z, min(1.0, math.erfc(abs(z) / math.sqrt(2.0)))
test_wilcoxon_signed_rank_test.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from wilcoxon_signed_rank_test import (
doubled_midranks, signed_rank_counts, tie_sizes, wilcoxon_normal, wilcoxon_signed_rank,
)
# 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)]
MIXED = [1.8, -0.6, 3.1, 2.4, -1.3, 0.9, 2.2, 0.0, 1.5, -0.4]
def brute_force(d: list[float]) -> tuple[Fraction, Fraction, Fraction]:
"""W+ and its tails by listing all 2^n sign vectors on the observed |d| (midranks)."""
kept = [v for v in d if v != 0]
n = len(kept)
a = [abs(v) for v in kept]
ranks = []
for v in a: # midrank = (number below) + (number equal + 1) / 2
below = sum(1 for t in a if t < v)
equal = sum(1 for t in a if t == v)
ranks.append(below + Fraction(equal + 1, 2))
w = sum(r for r, v in zip(ranks, kept) if v > 0)
upper = lower = 0
for signs in itertools.product((0, 1), repeat=n):
t = sum(r for r, e in zip(ranks, signs) if e)
upper += t >= w
lower += t <= w
return w, Fraction(upper, 2**n), Fraction(lower, 2**n)
def test_page_examples() -> None:
assert wilcoxon_signed_rank(DIFF, exact=True) == (45.0, Fraction(1, 256))
assert wilcoxon_signed_rank(MIXED, exact=True) == (38.0, Fraction(19, 256))
assert wilcoxon_signed_rank(MIXED, "greater", exact=True) == (38.0, Fraction(19, 512))
assert wilcoxon_normal(DIFF)[1] == pytest.approx(0.0090906980, abs=1e-9)
assert wilcoxon_normal(MIXED)[1] == pytest.approx(0.0755605675, abs=1e-9)
assert signed_rank_counts([2, 4, 6, 8])[::2] == [1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1]
assert signed_rank_counts([2, 5, 5, 8]) == [1, 0, 1, 0, 0, 2, 0, 2, 1, 0, 2, 0, 1, 2, 0, 2,
0, 0, 1, 0, 1]
def test_against_all_sign_vectors() -> None:
rng = random.Random(3)
for _ in range(150):
n = rng.randint(0, 11)
d = [rng.choice([-1, 1]) * rng.randint(0, 6) for _ in range(n)] # many ties and zeros
w, upper, lower = brute_force(d)
got_w, got_g = wilcoxon_signed_rank(d, "greater", exact=True)
assert got_w == float(w)
assert got_g == upper
assert wilcoxon_signed_rank(d, "less", exact=True)[1] == lower
assert wilcoxon_signed_rank(d, exact=True)[1] == min(Fraction(1), 2 * min(upper, lower))
def test_counts_match_subsets() -> None:
for n in range(0, 11):
r2 = [2 * i for i in range(1, n + 1)]
c = signed_rank_counts(r2)
want = [0] * len(c)
for mask in range(2**n):
want[sum(r for i, r in enumerate(r2) if mask >> i & 1)] += 1
assert c == want
def test_null_mean_and_variance() -> None:
for values in ([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 3, 3, 3, 4, 5, 5]):
n = len(values)
r2 = doubled_midranks(values)
c = signed_rank_counts(r2)
total = 2**n
mean = sum(Fraction(s, 2) * cnt for s, cnt in enumerate(c)) / total
var = sum(Fraction(s, 2) ** 2 * cnt for s, cnt in enumerate(c)) / total - mean**2
ties = sum(t**3 - t for t in tie_sizes(values))
assert mean == Fraction(n * (n + 1), 4)
assert var == Fraction(n * (n + 1) * (2 * n + 1), 24) - Fraction(ties, 48)
def test_null_is_symmetric() -> None:
c = signed_rank_counts(doubled_midranks([1, 2, 2, 3, 5, 5, 5, 8]))
assert c == c[::-1]
def test_critical_value_n20() -> None:
c = signed_rank_counts([2 * i for i in range(1, 21)])
assert Fraction(sum(c[: 2 * 52 + 1]), 2**20) <= Fraction(25, 1000)
assert Fraction(sum(c[: 2 * 53 + 1]), 2**20) > Fraction(25, 1000)
def test_size_under_symmetry_monte_carlo() -> None:
rng = random.Random(5)
n, r, alpha = 15, 2000, 0.05
hits = sum(wilcoxon_signed_rank([rng.gauss(0.0, 1.0) for _ in range(n)])[1] <= alpha
for _ in range(r))
assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)
def test_skewed_null_median_is_not_enough() -> None:
# Median 0 but not symmetric: the test rejects far more often than alpha.
rng = random.Random(11)
n, r, alpha = 20, 2000, 0.05
hits = sum(wilcoxon_signed_rank([rng.expovariate(1.0) - math.log(2.0)
for _ in range(n)])[1] <= alpha for _ in range(r))
assert hits / r > alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)
def test_edges() -> None:
assert wilcoxon_signed_rank([0.0, 0.0], exact=True) == (0.0, 1)
assert wilcoxon_normal([0.0]) == (0.0, 1.0)
with pytest.raises(ValueError):
wilcoxon_signed_rank([1.0], "both")
assert wilcoxon_signed_rank([3.0, 4.0], mu0=3.0, exact=True) == (1.0, 1)
wilcoxon_signed_rank_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.
"""Entry point named after the slug. The code lives in wilcoxon_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from wilcoxon_core import (
ALTERNATIVES, doubled_midranks, signed_rank_counts, tie_sizes, wilcoxon_normal,
wilcoxon_signed_rank,
)
__all__ = ["ALTERNATIVES", "doubled_midranks", "signed_rank_counts", "tie_sizes",
"wilcoxon_normal", "wilcoxon_signed_rank"]
History
Frank Wilcoxon, a chemist at the American Cyanamid Company, gave the signed-rank test for paired comparisons and the rank-sum test for two samples in one paper of 1945, with tables for small samples, as quick replacements for the t-test. Hodges and Lehmann (1956) showed that the loss of efficiency against the t-test is small, which changed the view of rank tests from quick approximations to serious tools. Pratt (1959) studied the handling of zeros and ties.
References
- Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 3 (the one-sample location problem), the section on the Wilcoxon signed rank test
- E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on paired comparisons and the one-sample problem (the signed-rank test, ties, zeros and efficiency)
- Frank Wilcoxon, Individual comparisons by ranking methods, Biometrics Bulletin 1(6), 1945, pp. 80 to 83 (the paired-sample test by signed ranks, with a table of exact tail probabilities)
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 8KPP1Q Edit this page History Report an error Markdown