Algorithm Search⌘K

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
Properties
deterministicexact error boundsonlineiterative
Origin
Abraham Wald, 1945

The sequential probability ratio test (SPRT) decides between two simple hypotheses, H0H_0: the observations have density f0f_0, and H1H_1: they have density f1f_1, 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 (a,b)(a, b) set by the target error rates α\alpha and β\beta. Wald's thresholds guarantee error rates at most α/(1−β)\alpha/(1 - \beta) and β/(1−α)\beta/(1 - \alpha) 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 X1,X2,…X_1, X_2, \ldots are i.i.d. with density ff with respect to a measure ν\nu, and f∈{f0,f1}f \in \{f_0, f_1\}. The densities f0f_0 and f1f_1 are positive on the same set, and they differ on a set of positive ν\nu-measure. Given α,β>0\alpha, \beta > 0 with α+β<1\alpha + \beta < 1, find a stopping rule NN, which may depend only on the observations seen so far, and a decision at time NN such that the realized error rates

α′=P0(reject H0),β′=P1(accept H0)\alpha' = P_0(\text{reject } H_0), \qquad \beta' = P_1(\text{accept } H_0)

are about α\alpha and β\beta, and the average sample numbers E0[N]E_0[N] and E1[N]E_1[N] are small. Write Zi=log⁡f1(Xi)−log⁡f0(Xi)Z_i = \log f_1(X_i) - \log f_0(X_i) and Λn=Z1+⋯+Zn\Lambda_n = Z_1 + \cdots + Z_n.

The algorithm

  1. SPRT(x_1, x_2, ..., f_0, f_1, α, β) ▷ α, β > 0 and α + β < 1
  2. 1a ← log(β / (1 - α)), b ← log((1 - β) / α)
  3. 2Λ ← 0, n ← 0
  4. 3for each new observation x do
  5. 4n ← n + 1
  6. 5Λ ← Λ + log f_1(x) - log f_0(x) ▷ Λ is now Λ_n
  7. 6if Λ ≥ b then return (reject H_0, n)
  8. 7if Λ ≤ a then return (accept H_0, n)

Line L1 sets Wald's thresholds. In the ratio scale they are A=eb=(1−β)/αA = e^b = (1 - \beta)/\alpha and B=ea=β/(1−α)B = e^a = \beta/(1 - \alpha), and B<1<AB < 1 < A because α+β<1\alpha + \beta < 1. Lines L4 and L5 add one log likelihood ratio per observation, so Λ\Lambda is a random walk with negative drift −D(f0 ∥ f1)-D(f_0 \,\|\, f_1) under H0H_0 and positive drift D(f1 ∥ f0)D(f_1 \,\|\, f_0) under H1H_1, where DD is the Kullback-Leibler divergence. Lines L6 and L7 stop at the first exit from (a,b)(a, b); 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, f0f_0: heads with probability 0.50.5, against f1f_1: heads with probability 0.80.8, with α=β=0.1\alpha = \beta = 0.1. Then b=log⁡9≈2.197b = \log 9 \approx 2.197 and a=−2.197a = -2.197. A head adds log⁡(0.8/0.5)=log⁡1.6≈0.470\log(0.8/0.5) = \log 1.6 \approx 0.470 and a tail adds log⁡(0.2/0.5)=log⁡0.4≈−0.916\log(0.2/0.5) = \log 0.4 \approx -0.916. On the flips HHTHHHHH:

nn 1 2 3 4 5 6 7 8
flip H H T H H H H H
Λn\Lambda_n 0.470 0.940 0.024 0.494 0.964 1.434 1.904 2.374

At n=8n = 8, Λ8=7log⁡1.6+log⁡0.4≈2.374≥2.197\Lambda_8 = 7\log 1.6 + \log 0.4 \approx 2.374 \ge 2.197, so the test rejects H0H_0.

The state of this test after nn 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 α′\alpha' 0.08443 bound α/(1−β)=0.1111\alpha/(1 - \beta) = 0.1111
type II error β′\beta' 0.07738 bound β/(1−α)=0.1111\beta/(1 - \alpha) = 0.1111
E0[N]E_0[N] 9.365 approximation 7.877
E1[N]E_1[N] 10.474 approximation 9.120

The fixed-sample binomial test with α≤0.1\alpha \le 0.1 and β≤0.1\beta \le 0.1 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, H0H_0: N(0,1)N(0, 1) against H1H_1: N(0.5,1)N(0.5, 1) with α=β=0.05\alpha = \beta = 0.05, 20 000 simulated runs under each hypothesis gave α′≈0.040\alpha' \approx 0.040, β′≈0.039\beta' \approx 0.039 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 n=(2×1.645/0.5)2≈43.3n = (2 \times 1.645 / 0.5)^2 \approx 43.3, so 44 observations.

Correctness

Four facts, proved in full below.

  1. Termination. Under any i.i.d. law for which Z1Z_1 is not almost surely 0, in particular under H0H_0 and H1H_1, there are m≥1m \ge 1 and δ>0\delta > 0 with P(N>km)≤(1−δ)kP(N > km) \le (1 - \delta)^k. Any block of mm consecutive increments that are all larger than cc, with mc>b−amc > b - a, forces an exit. So N<∞N < \infty almost surely and E[N]<∞E[N] < \infty.
  2. Wald's error bounds. On {N=n}\{N = n\}, the measures P1P_1 and P0P_0 differ by the factor eΛne^{\Lambda_n}. On rejection eΛN≥Ae^{\Lambda_N} \ge A and on acceptance eΛN≤Be^{\Lambda_N} \le B, so 1−β′≥Aα′1 - \beta' \ge A\alpha' and β′≤B(1−α′)\beta' \le B(1 - \alpha'). These give
α′≤α1−β,β′≤β1−α,α′+β′≤α+β.\alpha' \le \frac{\alpha}{1 - \beta}, \qquad \beta' \le \frac{\beta}{1 - \alpha}, \qquad \alpha' + \beta' \le \alpha + \beta.

The bound on α′\alpha' also follows from Ville's inequality, because eΛne^{\Lambda_n} is a test martingale under H0H_0. 3. The average sample number. If Ej∣Z1∣<∞E_j|Z_1| < \infty, Wald's equation gives Ej[ΛN]=Ej[Z1] Ej[N]E_j[\Lambda_N] = E_j[Z_1]\,E_j[N] exactly. Replacing ΛN\Lambda_N by bb on rejection and aa on acceptance, that is, ignoring the overshoot, gives Wald's approximations

E0[N]≈αb+(1−α)a−D(f0 ∥ f1),E1[N]≈(1−β)b+βaD(f1 ∥ f0).E_0[N] \approx \frac{\alpha b + (1 - \alpha) a}{-D(f_0 \,\|\, f_1)}, \qquad E_1[N] \approx \frac{(1 - \beta) b + \beta a}{D(f_1 \,\|\, f_0)}.

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 P0(reject)≤α′P_0(\text{reject}) \le \alpha' and P1(accept)≤β′P_1(\text{accept}) \le \beta', where α′\alpha' and β′\beta' are the error rates of the SPRT itself, none has a smaller E0[N]E_0[N] or a smaller E1[N]E_1[N]. 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. X1,X2,…X_1, X_2, \ldots are i.i.d., Zi=log⁡f1(Xi)−log⁡f0(Xi)Z_i = \log f_1(X_i) - \log f_0(X_i), Λn=Z1+⋯+Zn\Lambda_n = Z_1 + \cdots + Z_n is the value of Λ\Lambda after line L5 in iteration nn, and a<0<ba < 0 < b are the thresholds of line L1. The test stops at

N=inf⁡{n≥1:Λn∉(a,b)},N = \inf\{n \ge 1 : \Lambda_n \notin (a, b)\},

rejects H0H_0 if ΛN≥b\Lambda_N \ge b (line L6) and accepts it if ΛN≤a\Lambda_N \le a (line L7). The two cases cannot both hold since a<ba < b. PjP_j and EjE_j refer to the law under which the XiX_i have density fjf_j. We assume that f0f_0 and f1f_1 are positive on the same set and are not equal ν\nu-almost everywhere, so Z1Z_1 is finite and not almost surely 0 under P0P_0 and P1P_1.

Lemma 1 (termination). Let PP be any law of the XiX_i under which they are i.i.d. and P(Z1=0)<1P(Z_1 = 0) < 1. Then there are an integer m≥1m \ge 1 and δ>0\delta > 0 such that P(N>km)≤(1−δ)kP(N > km) \le (1 - \delta)^k for every k≥0k \ge 0. In particular P(N<∞)=1P(N < \infty) = 1 and E[Nr]<∞E[N^r] < \infty for every r≥1r \ge 1.

Proof. Since P(Z1≠0)>0P(Z_1 \ne 0) > 0, either P(Z1>c)>0P(Z_1 > c) > 0 or P(Z1<−c)>0P(Z_1 < -c) > 0 for some c>0c > 0. Take the first case; the second is symmetric. Choose mm with mc>b−amc > b - a and let δ=P(Z1>c)m>0\delta = P(Z_1 > c)^m > 0. For k≥1k \ge 1, let GkG_k be the event that Zi>cZ_i > c for all ii in the block (k−1)m<i≤km(k-1)m < i \le km. If N>(k−1)mN > (k-1)m, then Λ(k−1)m∈(a,b)\Lambda_{(k-1)m} \in (a, b), or k=1k = 1 and Λ0=0∈(a,b)\Lambda_0 = 0 \in (a, b). On GkG_k the walk then gains more than mc>b−amc > b - a inside the block, so it cannot stay in (a,b)(a, b) for the whole block, and N≤kmN \le km. Hence {N>km}⊆{N>(k−1)m}∩Gkc\{N > km\} \subseteq \{N > (k-1)m\} \cap G_k^c. The event {N>(k−1)m}\{N > (k-1)m\} depends on X1,…,X(k−1)mX_1, \ldots, X_{(k-1)m} and GkG_k on the next block, so they are independent, and

P(N>km)≤P(N>(k−1)m)(1−δ).P(N > km) \le P(N > (k-1)m)(1 - \delta).

Induction gives P(N>km)≤(1−δ)kP(N > km) \le (1 - \delta)^k. Then P(N=∞)≤lim⁡k(1−δ)k=0P(N = \infty) \le \lim_k (1 - \delta)^k = 0, and E[Nr]≤∑k≥0((k+1)m)r(1−δ)k<∞E[N^r] \le \sum_{k \ge 0} ((k+1)m)^r (1 - \delta)^k < \infty. □\square

Both f0f_0 and f1f_1 give laws that satisfy the hypothesis of Lemma 1, so under H0H_0 and under H1H_1 the test stops almost surely with a decision.

Lemma 2 (change of measure). For every event EE that is determined by NN and X1,…,XNX_1, \ldots, X_N, with E⊆{N<∞}E \subseteq \{N < \infty\},

P1(E)=E0[eΛN 1E].P_1(E) = E_0\bigl[e^{\Lambda_N}\,\mathbf 1_E\bigr].

Proof. Split EE into the disjoint events En=E∩{N=n}E_n = E \cap \{N = n\}. Since NN is a stopping time, EnE_n is determined by X1,…,XnX_1, \ldots, X_n, so 1En=gn(X1,…,Xn)\mathbf 1_{E_n} = g_n(X_1, \ldots, X_n) for a measurable gng_n with values in {0,1}\{0, 1\}. On the set where f0f_0 is positive,

P1(En)=∫gn∏i=1nf1(xi) ν(dxi)=∫gn∏i=1nf1(xi)f0(xi)∏i=1nf0(xi) ν(dxi)=E0[eΛn1En],P_1(E_n) = \int g_n \prod_{i=1}^n f_1(x_i)\,\nu(dx_i) = \int g_n \prod_{i=1}^n \frac{f_1(x_i)}{f_0(x_i)}\prod_{i=1}^n f_0(x_i)\,\nu(dx_i) = E_0\bigl[e^{\Lambda_n}\mathbf 1_{E_n}\bigr],

because f0f_0 and f1f_1 are positive on the same set. Add over nn; both sides are sums of nonnegative terms. □\square

Theorem 1 (Wald's bounds). Let α′=P0(ΛN≥b)\alpha' = P_0(\Lambda_N \ge b) and β′=P1(ΛN≤a)\beta' = P_1(\Lambda_N \le a). With A=eb=(1−β)/αA = e^b = (1 - \beta)/\alpha and B=ea=β/(1−α)B = e^a = \beta/(1 - \alpha),

1−β′≥A α′,β′≤B (1−α′),1 - \beta' \ge A\,\alpha', \qquad \beta' \le B\,(1 - \alpha'),

and therefore

α′≤α1−β,β′≤β1−α,α′+β′≤α+β.\alpha' \le \frac{\alpha}{1 - \beta}, \qquad \beta' \le \frac{\beta}{1 - \alpha}, \qquad \alpha' + \beta' \le \alpha + \beta.

Proof. Let R={N<∞,ΛN≥b}R = \{N < \infty, \Lambda_N \ge b\} and C={N<∞,ΛN≤a}C = \{N < \infty, \Lambda_N \le a\}. By Lemma 1, P0(R)+P0(C)=1P_0(R) + P_0(C) = 1 and P1(R)+P1(C)=1P_1(R) + P_1(C) = 1, so P0(C)=1−α′P_0(C) = 1 - \alpha' and P1(R)=1−β′P_1(R) = 1 - \beta'. On RR, eΛN≥Ae^{\Lambda_N} \ge A, and on CC, eΛN≤Be^{\Lambda_N} \le B. Lemma 2 gives

1−β′=P1(R)=E0[eΛN1R]≥A P0(R)=A α′,1 - \beta' = P_1(R) = E_0[e^{\Lambda_N}\mathbf 1_R] \ge A\,P_0(R) = A\,\alpha',
β′=P1(C)=E0[eΛN1C]≤B P0(C)=B (1−α′).\beta' = P_1(C) = E_0[e^{\Lambda_N}\mathbf 1_C] \le B\,P_0(C) = B\,(1 - \alpha').

From the first inequality, α′≤(1−β′)/A≤1/A=α/(1−β)\alpha' \le (1 - \beta')/A \le 1/A = \alpha/(1 - \beta). From the second, β′≤B=β/(1−α)\beta' \le B = \beta/(1 - \alpha). For the sum, insert the values of AA and BB and clear the denominators, which are positive since α+β<1\alpha + \beta < 1:

α(1−β′)≥(1−β)α′and(1−α)β′≤β(1−α′).\alpha(1 - \beta') \ge (1 - \beta)\alpha' \quad\text{and}\quad (1 - \alpha)\beta' \le \beta(1 - \alpha').

Rewrite them as α′−α≤α′β−αβ′\alpha' - \alpha \le \alpha'\beta - \alpha\beta' and β′−β≤αβ′−α′β\beta' - \beta \le \alpha\beta' - \alpha'\beta. Their sum is α′+β′−α−β≤0\alpha' + \beta' - \alpha - \beta \le 0. □\square

The first two bounds can fail to be tight only through the overshoot: if ΛN\Lambda_N were exactly bb on RR and exactly aa on CC, the two inequalities of the proof would be equalities, and solving them would give α′=α\alpha' = \alpha and β′=β\beta' = \beta.

Theorem 2 (average sample number). Let j∈{0,1}j \in \{0, 1\} and suppose Ej∣Z1∣<∞E_j|Z_1| < \infty and μj=Ej[Z1]≠0\mu_j = E_j[Z_1] \ne 0. Then

Ej[N]=Ej[ΛN]μj,μ0=−D(f0 ∥ f1),μ1=D(f1 ∥ f0).E_j[N] = \frac{E_j[\Lambda_N]}{\mu_j}, \qquad \mu_0 = -D(f_0 \,\|\, f_1), \qquad \mu_1 = D(f_1 \,\|\, f_0).

If the overshoot is ignored, that is, if ΛN\Lambda_N is replaced by bb on rejection and by aa on acceptance, and the error probabilities are replaced by α\alpha and β\beta, this gives Wald's approximations

E0[N]≈αb+(1−α)a−D(f0 ∥ f1),E1[N]≈(1−β)b+βaD(f1 ∥ f0).E_0[N] \approx \frac{\alpha b + (1 - \alpha)a}{-D(f_0 \,\|\, f_1)}, \qquad E_1[N] \approx \frac{(1 - \beta)b + \beta a}{D(f_1 \,\|\, f_0)}.

Proof. By Lemma 1, Ej[N]<∞E_j[N] < \infty. The ZiZ_i are i.i.d. and integrable under PjP_j, and {N≥i}={N≤i−1}c\{N \ge i\} = \{N \le i - 1\}^c depends only on Z1,…,Zi−1Z_1, \ldots, Z_{i-1}, so it is independent of ZiZ_i. Wald's equation gives Ej[ΛN]=μjEj[N]E_j[\Lambda_N] = \mu_j E_j[N] exactly; for completeness,

Ej[ΛN]=Ej[∑i≥1Zi1{N≥i}]=∑i≥1μjPj(N≥i)=μjEj[N],E_j[\Lambda_N] = E_j\Bigl[\sum_{i \ge 1} Z_i \mathbf 1\{N \ge i\}\Bigr] = \sum_{i \ge 1} \mu_j P_j(N \ge i) = \mu_j E_j[N],

where the exchange of sum and expectation holds because ∑iEj[∣Zi∣1{N≥i}]=Ej∣Z1∣ Ej[N]<∞\sum_i E_j[|Z_i|\mathbf 1\{N \ge i\}] = E_j|Z_1|\,E_j[N] < \infty. The values of μj\mu_j are the definitions of the divergences:

μ0=∫f0log⁡f1f0 dν=−D(f0 ∥ f1),μ1=∫f1log⁡f1f0 dν=D(f1 ∥ f0).\mu_0 = \int f_0 \log\frac{f_1}{f_0}\,d\nu = -D(f_0 \,\|\, f_1), \qquad \mu_1 = \int f_1 \log\frac{f_1}{f_0}\,d\nu = D(f_1 \,\|\, f_0).

Both are nonzero because f0≠f1f_0 \ne f_1 on a set of positive measure. Finally, E0[ΛN]=α′E0[ΛN∣R]+(1−α′)E0[ΛN∣C]E_0[\Lambda_N] = \alpha' E_0[\Lambda_N \mid R] + (1 - \alpha')E_0[\Lambda_N \mid C], and the approximation replaces the conditional means by bb and aa and α′\alpha' by α\alpha; the same holds under P1P_1 with 1−β′1 - \beta' and β′\beta'. □\square

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 Λ=Λn\Lambda = \Lambda_n after iteration nn, by induction on nn: Λ=0=Λ0\Lambda = 0 = \Lambda_0 before the loop, and line L5 adds ZnZ_n. Lines L6 and L7 return at the first nn with Λn≥b\Lambda_n \ge b or Λn≤a\Lambda_n \le a, which is NN, with the decision described above. By Lemma 1 the loop ends with probability 1 under H0H_0 and H1H_1, and by Theorem 1 the decision has error probabilities α′≤α/(1−β)\alpha' \le \alpha/(1 - \beta) and β′≤β/(1−α)\beta' \le \beta/(1 - \alpha). ■\blacksquare

Complexity

Each observation costs one evaluation of log⁡f1−log⁡f0\log f_1 - \log f_0, one addition and two comparisons, so the time is Θ(n)\Theta(n) for the nn observations read, and the extra space is Θ(1)\Theta(1). The number read is the random stopping time NN: 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 O(nmax⁡2)O(n_{\max}^2) for a horizon nmax⁡n_{\max}, since after nn flips only the number of heads matters.

Properties

  • Exact one-sided guarantees. The bounds of fact 2 hold for every pair f0,f1f_0, f_1 and need no approximation. The nominal α\alpha and β\beta themselves are not guaranteed: in the worst case α′\alpha' can reach α/(1−β)\alpha/(1 - \beta).
  • Conservative in practice. The overshoot makes α′\alpha' and β′\beta' smaller than α\alpha and β\beta for most models, as in both examples.
  • Valid under optional stopping for H0H_0. Since eΛne^{\Lambda_n} is a test martingale under H0H_0, stopping the test early, or ignoring the lower threshold, keeps the type I error at most 1/A1/A.
  • Unbounded sample size. NN has no deterministic upper bound, although P(N>n)P(N > n) decays exponentially.
  • Sensitive to the alternative. If the truth is neither f0f_0 nor f1f_1, the walk may have drift near 0, and E[N]E[N] is then largest.

Variants and improvements

  • Composite hypotheses with an indifference zone. For a one-parameter family with monotone likelihood ratio, the SPRT of θ0\theta_0 against θ1>θ0\theta_1 > \theta_0 is used to test θ≤θ0\theta \le \theta_0 against θ≥θ1\theta \ge \theta_1. Its rejection probability, the operating characteristic, is monotone in θ\theta, so the error bounds at θ0\theta_0 and θ1\theta_1 hold over each side.
  • Truncated SPRT. Stop at a maximum nmax⁡n_{\max} and decide by the sign of Λ\Lambda there. The error rates change slightly; the dynamic program of the example computes them exactly for discrete data.
  • Mixture SPRT. Replace f1f_1 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 f0f_0 to f1f_1.
  • 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 f0f_0 and f1f_1. 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 f0(x)=0<f1(x)f_0(x) = 0 < f_1(x), then log⁡f0(x)=−∞\log f_0(x) = -\infty 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 nn had been fixed.
  • Changing the plan midway. Changing f1f_1, α\alpha or β\beta after seeing the data voids the bounds, except for the option to stop early under H0H_0 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.

sprt_core.pyI0RawGitHub
# 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 AA and BB 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

  1. 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
  2. Abraham Wald, Sequential Analysis, Wiley, 1947, reprinted by Dover, 2004, Chapter 3 (the sequential probability ratio test) and the appendix (the fundamental identity)
  3. 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
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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