Algorithmcore
Sequential probability ratio test
Also called SPRT, Wald's sequential test.
Wald's test that reads one observation at a time and stops when the likelihood ratio leaves an interval (B, A). No test with its error rates has a smaller expected sample size.
- Time
- Θ(n) worst
- Space
- Θ(1) extra
- Where
- n = the number of observations read before the test stops, a random stopping time
- Model
- Real RAM
- Properties
- deterministicexact error boundsonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Abraham Wald, 1945
The sequential probability ratio test (SPRT) decides between two simple hypotheses, : the observations have density , and : they have density , by reading one observation at a time. After each one it updates the log likelihood ratio and stops as soon as it leaves an interval set by the target error rates and . Wald's thresholds guarantee error rates at most and with no approximation, and the expected number of observations is often half of what a fixed-sample test of the same strength needs. Wald and Wolfowitz proved that no sequential test with the same error probabilities has a smaller expected sample size under either hypothesis.
In plain words
You want to know whether a coin is fair or biased toward heads, and each flip costs money. Keep a score. A head is more likely under the biased coin, so it adds to the score; a tail subtracts. The amounts come from how much more likely each outcome is under one answer than under the other. Before you start, set an upper line and a lower line from how often you accept being wrong each way. Flip until the score crosses a line. Cross the upper line and you declare the coin biased; cross the lower line and you declare it fair. When the evidence is clear you stop early. When it is mixed you keep going. On average you need far fewer flips than a plan that fixes the number in advance.
The problem
Observations are i.i.d. with density with respect to a measure , and . The densities and are positive on the same set, and they differ on a set of positive -measure. Given with , find a stopping rule , which may depend only on the observations seen so far, and a decision at time such that the realized error rates
are about and , and the average sample numbers and are small. Write and .
The algorithm
SPRT(x_1, x_2, ..., f_0, f_1, α, β) ▷ α, β > 0 and α + β < 1- 1
a ← log(β / (1 - α)), b ← log((1 - β) / α) - 2
Λ ← 0, n ← 0 - 3
for each new observation x do - 4
n ← n + 1 - 5
Λ ← Λ + log f_1(x) - log f_0(x) ▷ Λ is now Λ_n - 6
if Λ ≥ b then return (reject H_0, n) - 7
if Λ ≤ a then return (accept H_0, n)
Line L1 sets Wald's thresholds. In the ratio scale they are and , and because . Lines L4 and L5 add one log likelihood ratio per observation, so is a random walk with negative drift under and positive drift under , where is the Kullback-Leibler divergence. Lines L6 and L7 stop at the first exit from ; the walk usually jumps past the threshold, and this overshoot makes the true error rates smaller than the nominal ones.
Example
Test a fair coin, : heads with probability , against : heads with probability , with . Then and . A head adds and a tail adds . On the flips HHTHHHHH:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
| flip | H | H | T | H | H | H | H | H |
| 0.470 | 0.940 | 0.024 | 0.494 | 0.964 | 1.434 | 1.904 | 2.374 |
At , , so the test rejects .
The state of this test after flips is the number of heads, so a dynamic program over (flips, heads) gives its exact operating characteristics:
| quantity | exact | Wald's value |
|---|---|---|
| type I error | 0.08443 | bound |
| type II error | 0.07738 | bound |
| 9.365 | approximation 7.877 | |
| 10.474 | approximation 9.120 |
The fixed-sample binomial test with and needs 19 flips (reject when there are at least 13 heads; its errors are 0.0835 and 0.0676). The SPRT uses about half as many on average.
For normal data, : against : with , 20 000 simulated runs under each hypothesis gave , and an average sample number of about 24.1 under both, against Wald's approximation 21.2. The one-sided fixed-sample z-test needs , so 44 observations.
Correctness
Four facts, proved in full below.
- Termination. Under any i.i.d. law for which is not almost surely 0, in particular under and , there are and with . Any block of consecutive increments that are all larger than , with , forces an exit. So almost surely and .
- Wald's error bounds. On , the measures and differ by the factor . On rejection and on acceptance , so and . These give
The bound on also follows from Ville's inequality, because is a test martingale under . 3. The average sample number. If , Wald's equation gives exactly. Replacing by on rejection and on acceptance, that is, ignoring the overshoot, gives Wald's approximations
These are approximations, not bounds. In the coin example they are below the exact values by 1.5 and 1.4 observations. 4. Optimality. Wald and Wolfowitz (1948) proved that among all tests, sequential or not, with and , where and are the error rates of the SPRT itself, none has a smaller or a smaller . This page cites that theorem and does not prove it.
Proof: The SPRT stops, obeys Wald's error bounds, and has Wald's average sample number up to the overshootfull
Notation is that of the page. are i.i.d., , is the value of after line L5 in iteration , and are the thresholds of line L1. The test stops at
rejects if (line L6) and accepts it if (line L7). The two cases cannot both hold since . and refer to the law under which the have density . We assume that and are positive on the same set and are not equal -almost everywhere, so is finite and not almost surely 0 under and .
Lemma 1 (termination). Let be any law of the under which they are i.i.d. and . Then there are an integer and such that for every . In particular and for every .
Proof. Since , either or for some . Take the first case; the second is symmetric. Choose with and let . For , let be the event that for all in the block . If , then , or and . On the walk then gains more than inside the block, so it cannot stay in for the whole block, and . Hence . The event depends on and on the next block, so they are independent, and
Induction gives . Then , and .
Both and give laws that satisfy the hypothesis of Lemma 1, so under and under the test stops almost surely with a decision.
Lemma 2 (change of measure). For every event that is determined by and , with ,
Proof. Split into the disjoint events . Since is a stopping time, is determined by , so for a measurable with values in . On the set where is positive,
because and are positive on the same set. Add over ; both sides are sums of nonnegative terms.
Theorem 1 (Wald's bounds). Let and . With and ,
and therefore
Proof. Let and . By Lemma 1, and , so and . On , , and on , . Lemma 2 gives
From the first inequality, . From the second, . For the sum, insert the values of and and clear the denominators, which are positive since :
Rewrite them as and . Their sum is .
The first two bounds can fail to be tight only through the overshoot: if were exactly on and exactly on , the two inequalities of the proof would be equalities, and solving them would give and .
Theorem 2 (average sample number). Let and suppose and . Then
If the overshoot is ignored, that is, if is replaced by on rejection and by on acceptance, and the error probabilities are replaced by and , this gives Wald's approximations
Proof. By Lemma 1, . The are i.i.d. and integrable under , and depends only on , so it is independent of . Wald's equation gives exactly; for completeness,
where the exchange of sum and expectation holds because . The values of are the definitions of the divergences:
Both are nonzero because on a set of positive measure. Finally, , and the approximation replaces the conditional means by and and by ; the same holds under with and .
The replacement is the only approximation, and it is not a bound in general. In the examples of the page, Wald's values are below the exact average sample numbers.
Correctness of the procedure. Lines L2 to L5 maintain after iteration , by induction on : before the loop, and line L5 adds . Lines L6 and L7 return at the first with or , which is , with the decision described above. By Lemma 1 the loop ends with probability 1 under and , and by Theorem 1 the decision has error probabilities and .
Complexity
Each observation costs one evaluation of , one addition and two comparisons, so the time is for the observations read, and the extra space is . The number read is the random stopping time : it has an exponential tail by fact 1, and its mean is given by fact 3. For the exact operating characteristics of a discrete model, the dynamic program of the example costs for a horizon , since after flips only the number of heads matters.
Properties
- Exact one-sided guarantees. The bounds of fact 2 hold for every pair and need no approximation. The nominal and themselves are not guaranteed: in the worst case can reach .
- Conservative in practice. The overshoot makes and smaller than and for most models, as in both examples.
- Valid under optional stopping for . Since is a test martingale under , stopping the test early, or ignoring the lower threshold, keeps the type I error at most .
- Unbounded sample size. has no deterministic upper bound, although decays exponentially.
- Sensitive to the alternative. If the truth is neither nor , the walk may have drift near 0, and is then largest.
Variants and improvements
- Composite hypotheses with an indifference zone. For a one-parameter family with monotone likelihood ratio, the SPRT of against is used to test against . Its rejection probability, the operating characteristic, is monotone in , so the error bounds at and hold over each side.
- Truncated SPRT. Stop at a maximum and decide by the sign of there. The error rates change slightly; the dynamic program of the example computes them exactly for discrete data.
- Mixture SPRT. Replace by a mixture over a range of alternatives, and drop the lower threshold. The result is the mixture SPRT, which tests a point null against a composite alternative and gives always valid p-values.
- CUSUM. Running an SPRT with lower threshold 0 and restarting it each time it accepts gives Page's CUSUM procedure for detecting a change from to .
- Grouped data. When observations arrive in batches and can be analysed only a few times, a group sequential design replaces the continuous boundary.
- Applications. Statistical model checking runs an SPRT on simulation outcomes, and radar and communication receivers use it for signal detection.
When to use it
Use the SPRT when observations arrive one at a time, each one has a cost, and the question is a choice between two well-defined hypotheses, or two points that bound an indifference zone: acceptance sampling, model checking by simulation, and quick screening decisions. Use a fixed-sample test when the data come in one batch or when an unbiased estimate of the effect size matters more than the number of observations. Use the mixture SPRT or a confidence sequence when the alternative is not a single point.
Pitfalls
- Wrong alternative. The thresholds give guarantees only at and . If the true effect is half of the planned one, the expected sample size can exceed the fixed-sample size of the planned test.
- Reading the approximations as bounds. Wald's average sample numbers ignore the overshoot and are too small, as the example shows. Compute the exact values by dynamic programming or simulation when they matter.
- Densities that are not mutually absolutely continuous. If , then and the test must stop at once with rejection. Code that computes the log ratio in floating point must handle this case.
- Estimation after stopping. The sample mean at the stopping time is biased, because the test stops when the data look extreme. Do not report it as if had been fixed.
- Changing the plan midway. Changing , or after seeing the data voids the bounds, except for the option to stop early under noted above.
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/sequential-probability-ratio-test/. The authors are listed in prov/9JY1HF.jsonl.
"""Wald's sequential probability ratio test (SPRT).
The test reads i.i.d. observations one at a time and keeps the log likelihood
ratio Lambda_n = sum log f1(x_i) - log f0(x_i). It stops as soon as Lambda_n
leaves the open interval (a, b) with Wald's thresholds
a = log(beta / (1 - alpha)) and b = log((1 - beta) / alpha).
Cost: O(1) time and O(1) memory per observation. The number of observations N
is random; under either hypothesis E[N] is finite when f0 and f1 differ.
"""
import math
from collections.abc import Callable, Iterable
from fractions import Fraction
def wald_thresholds(alpha: float, beta: float) -> tuple[float, float]:
"""Wald's thresholds (a, b) for target error rates alpha, beta with alpha + beta < 1."""
if not (0.0 < alpha < 1.0 and 0.0 < beta < 1.0 and alpha + beta < 1.0):
raise ValueError("need 0 < alpha, beta and alpha + beta < 1")
return math.log(beta / (1.0 - alpha)), math.log((1.0 - beta) / alpha)
def sprt(stream: Iterable[float], log_f0: Callable[[float], float], log_f1: Callable[[float], float],
alpha: float, beta: float) -> tuple[str, int, float]:
"""Run the SPRT of H0: density f0 against H1: density f1 on the stream.
Returns (decision, n, Lambda_n) where decision is "reject H0", "accept H0",
or "no decision" if the stream ends first. Precondition: f0 and f1 are
positive on the same set, so every log ratio is finite. Cost O(1) per item.
"""
a, b = wald_thresholds(alpha, beta) # @line L1
lam = 0.0 # @line L2
n = 0 # @line L2
for x in stream: # @line L3
n += 1 # @line L4
lam += log_f1(x) - log_f0(x) # @line L5
if lam >= b: # @line L6
return "reject H0", n, lam # @line L6
if lam <= a: # @line L7
return "accept H0", n, lam # @line L7
return "no decision", n, lam
def bernoulli_sprt_exact(p0: float, p1: float, p: float, alpha: float, beta: float,
n_max: int) -> tuple[float, float, float, float]:
"""Exact operating characteristics of the Bernoulli SPRT, truncated at n_max.
The state after n draws is the number of heads h, since Lambda_n =
h log(p1/p0) + (n - h) log((1 - p1)/(1 - p0)). A forward dynamic program
over (n, h) gives, under the true head probability p,
(P(reject H0, N <= n_max), P(accept H0, N <= n_max), E[min(N, n_max)], P(N > n_max)).
Cost O(n_max^2).
"""
a, b = wald_thresholds(alpha, beta)
up, down = math.log(p1 / p0), math.log((1.0 - p1) / (1.0 - p0))
alive = {0: 1.0}
rej = acc = 0.0
e_n = 0.0
for n in range(1, n_max + 1):
e_n += sum(alive.values())
nxt: dict[int, float] = {}
for h, m in alive.items():
for dh, q in ((1, p), (0, 1.0 - p)):
h2 = h + dh
lam = h2 * up + (n - h2) * down
if lam >= b:
rej += m * q
elif lam <= a:
acc += m * q
else:
nxt[h2] = nxt.get(h2, 0.0) + m * q
alive = nxt
return rej, acc, e_n, sum(alive.values())
def bernoulli_sprt_moments_exact(p0: float, p1: float, p: Fraction, alpha: float, beta: float,
n_max: int) -> tuple[Fraction, Fraction]:
"""E[H_T] and E[T] in exact rational arithmetic, T = min(N, n_max), H_T = heads seen.
The stopping rule uses floating log ratios; the probabilities are exact
Fractions in p. Wald's equation says E[H_T] = p E[T] for the bounded
stopping time T.
"""
a, b = wald_thresholds(alpha, beta)
up, down = math.log(p1 / p0), math.log((1.0 - p1) / (1.0 - p0))
alive = {0: Fraction(1)}
e_h = Fraction(0)
e_t = Fraction(0)
for n in range(1, n_max + 1):
nxt: dict[int, Fraction] = {}
for h, m in alive.items():
for dh, q in ((1, p), (0, 1 - p)):
h2 = h + dh
lam = h2 * up + (n - h2) * down
if lam >= b or lam <= a or n == n_max:
e_h += m * q * h2
e_t += m * q * n
else:
nxt[h2] = nxt.get(h2, Fraction(0)) + m * q
alive = nxt
return e_h, e_t
def wald_asn(mean_step: float, p_upper: float, a: float, b: float) -> float:
"""Wald's ASN approximation E[N] = (p_upper b + (1 - p_upper) a) / E[Z], overshoot ignored."""
return (p_upper * b + (1.0 - p_upper) * a) / mean_step
sequential_probability_ratio_test.py 14 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequential-probability-ratio-test/. The authors are listed in prov/9JY1HF.jsonl.
"""Entry point named after the slug. The code lives in sprt_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from sprt_core import (
bernoulli_sprt_exact,
bernoulli_sprt_moments_exact,
sprt,
wald_asn,
wald_thresholds,
)
__all__ = ["bernoulli_sprt_exact", "bernoulli_sprt_moments_exact", "sprt", "wald_asn", "wald_thresholds"]
test_sequential_probability_ratio_test.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequential-probability-ratio-test/. The authors are listed in prov/9JY1HF.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from sequential_probability_ratio_test import (
bernoulli_sprt_exact,
bernoulli_sprt_moments_exact,
sprt,
wald_asn,
wald_thresholds,
)
def coin(p0: float, p1: float):
return (lambda x: math.log(p0 if x else 1.0 - p0)), (lambda x: math.log(p1 if x else 1.0 - p1))
def test_worked_example():
a, b = wald_thresholds(0.1, 0.1)
assert abs(b - math.log(9.0)) < 1e-12 and abs(a + math.log(9.0)) < 1e-12
lf0, lf1 = coin(0.5, 0.8)
decision, n, lam = sprt([1, 1, 0, 1, 1, 1, 1, 1], lf0, lf1, 0.1, 0.1)
assert (decision, n) == ("reject H0", 8)
assert abs(lam - (7 * math.log(1.6) + math.log(0.4))) < 1e-12
def test_accept_and_no_decision():
lf0, lf1 = coin(0.5, 0.8)
assert sprt([0, 0, 0], lf0, lf1, 0.1, 0.1)[:2] == ("accept H0", 3)
assert sprt([1, 0], lf0, lf1, 0.1, 0.1)[:2] == ("no decision", 2)
assert sprt([], lf0, lf1, 0.1, 0.1)[:2] == ("no decision", 0)
def test_bad_thresholds():
with pytest.raises(ValueError):
wald_thresholds(0.6, 0.5)
with pytest.raises(ValueError):
wald_thresholds(0.0, 0.1)
def brute_force(p0: float, p1: float, p: float, alpha: float, beta: float, n: int) -> tuple[float, float]:
"""Run the SPRT on every 0-1 sequence of length n and add up the probabilities."""
lf0, lf1 = coin(p0, p1)
rej = acc = 0.0
for seq in itertools.product((0, 1), repeat=n):
w = math.prod(p if x else 1.0 - p for x in seq)
d = sprt(seq, lf0, lf1, alpha, beta)[0]
rej += w * (d == "reject H0")
acc += w * (d == "accept H0")
return rej, acc
def test_dynamic_program_matches_enumeration():
for p0, p1, alpha, beta in ((0.5, 0.8, 0.1, 0.1), (0.3, 0.6, 0.05, 0.2), (0.6, 0.4, 0.1, 0.05)):
for p in (p0, p1, 0.5):
rej, acc, _, _ = bernoulli_sprt_exact(p0, p1, p, alpha, beta, 12)
r2, a2 = brute_force(p0, p1, p, alpha, beta, 12)
assert abs(rej - r2) < 1e-12 and abs(acc - a2) < 1e-12
@pytest.mark.parametrize("p0, p1, alpha, beta", [(0.5, 0.8, 0.1, 0.1), (0.3, 0.5, 0.05, 0.2),
(0.5, 0.6, 0.05, 0.05), (0.2, 0.1, 0.01, 0.1)])
def test_wald_error_bounds_exact(p0, p1, alpha, beta):
rej0, acc0, _, left0 = bernoulli_sprt_exact(p0, p1, p0, alpha, beta, 3000)
rej1, acc1, _, left1 = bernoulli_sprt_exact(p0, p1, p1, alpha, beta, 3000)
assert left0 < 1e-12 and left1 < 1e-12
a_err, b_err = rej0, acc1
assert a_err <= alpha / (1.0 - beta)
assert b_err <= beta / (1.0 - alpha)
assert a_err + b_err <= alpha + beta
# Ville: P0(Lambda ever reaches b) <= exp(-b) = alpha / (1 - beta) as well.
assert a_err <= math.exp(-wald_thresholds(alpha, beta)[1]) + 1e-15
def test_worked_example_operating_characteristics():
rej0, _, en0, _ = bernoulli_sprt_exact(0.5, 0.8, 0.5, 0.1, 0.1, 600)
_, acc1, en1, _ = bernoulli_sprt_exact(0.5, 0.8, 0.8, 0.1, 0.1, 600)
assert abs(rej0 - 0.08443) < 1e-5 and abs(acc1 - 0.07738) < 1e-5
assert abs(en0 - 9.365) < 1e-3 and abs(en1 - 10.474) < 1e-3
a, b = wald_thresholds(0.1, 0.1)
ez0 = 0.5 * math.log(1.6) + 0.5 * math.log(0.4)
ez1 = 0.8 * math.log(1.6) + 0.2 * math.log(0.4)
assert abs(wald_asn(ez0, 0.1, a, b) - 7.877) < 1e-3
assert abs(wald_asn(ez1, 0.9, a, b) - 9.120) < 1e-3
def test_walds_equation_exact():
for p in (Fraction(1, 2), Fraction(4, 5), Fraction(2, 3)):
for n_max in (5, 17, 30):
e_h, e_t = bernoulli_sprt_moments_exact(0.5, 0.8, p, 0.1, 0.1, n_max)
assert e_h == p * e_t
def test_normal_monte_carlo_against_wald_bounds():
rng = random.Random(11)
mu, alpha, beta = 0.5, 0.05, 0.05
lf0 = lambda x: -0.5 * x * x # noqa: E731
lf1 = lambda x: -0.5 * (x - mu) ** 2 # noqa: E731
reps = 4000
for theta, bound in ((0.0, alpha / (1 - beta)), (mu, beta / (1 - alpha))):
errors = 0
total = 0
def stream():
while True:
yield rng.gauss(theta, 1.0)
for _ in range(reps):
d, n, _ = sprt(stream(), lf0, lf1, alpha, beta)
errors += d == ("reject H0" if theta == 0.0 else "accept H0")
total += n
se = math.sqrt(bound * (1 - bound) / reps)
assert errors / reps < bound + 4 * se
# The ASN sits above Wald's overshoot-free value 21.2 and far below the fixed sample size 43.3.
assert 21.0 < total / reps < 28.0
def test_random_streams_against_direct_rule():
rng = random.Random(2026)
for _ in range(500):
p0 = rng.uniform(0.1, 0.9)
p1 = rng.uniform(0.1, 0.9)
if abs(p0 - p1) < 0.05:
continue
alpha, beta = rng.uniform(0.01, 0.2), rng.uniform(0.01, 0.2)
seq = [int(rng.random() < 0.5) for _ in range(rng.randint(0, 30))]
lf0, lf1 = coin(p0, p1)
a, b = math.log(beta / (1 - alpha)), math.log((1 - beta) / alpha)
want = ("no decision", len(seq))
lam = 0.0
for i, x in enumerate(seq, 1):
lam += math.log((p1 if x else 1 - p1) / (p0 if x else 1 - p0))
if lam >= b:
want = ("reject H0", i)
break
if lam <= a:
want = ("accept H0", i)
break
assert sprt(seq, lf0, lf1, alpha, beta)[:2] == want
History
Wald developed the test in 1943, in the Statistical Research Group at Columbia University, for wartime acceptance sampling, and published it in the Annals of Mathematical Statistics in 1945 with the inequalities for and and the approximations for the average sample number; his 1947 book Sequential Analysis gives the full theory. Wald and Wolfowitz (1948) proved that the SPRT minimizes the expected sample size under both hypotheses. Siegmund (1985) gives a modern treatment with corrected approximations for the overshoot.
References
- Abraham Wald, Sequential tests of statistical hypotheses, Annals of Mathematical Statistics 16(2) (1945), pages 117 to 186, the definition of the test, the inequalities for the thresholds A and B, and the approximation of the expected sample size
- Abraham Wald, Sequential Analysis, Wiley, 1947, reprinted by Dover, 2004, Chapter 3 (the sequential probability ratio test) and the appendix (the fundamental identity)
- A. Wald and J. Wolfowitz, Optimum character of the sequential probability ratio test, Annals of Mathematical Statistics 19(3) (1948), pages 326 to 339, the theorem that the SPRT minimizes the expected sample size under both hypotheses among tests with no larger error probabilities
- David Siegmund, Sequential Analysis, Tests and Confidence Intervals, Springer, 1985, Chapter II (the sequential probability ratio test, the approximations for the error probabilities and the expected sample size, and its optimality)
- Alexander Tartakovsky, Igor Nikiforov and Michèle Basseville, Sequential Analysis, Hypothesis Testing and Changepoint Detection, CRC Press, 2014, Chapter 3 (sequential hypothesis testing, two simple hypotheses)
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 9JY1HF Edit this page History Report an error Markdown