TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Amplification by Repetition

Amplification by Repetition

A Monte Carlo algorithm that errs with probability 1/31/3 sounds unreliable. It is not: run it a few dozen times with fresh random bits and combine the answers, and the error drops below 10−910^{-9}. This lesson works out how fast the error falls for one-sided and for two-sided error, introduces the median trick for numerical estimates, and explains why the constants 1/21/2 and 2/32/3 in the definitions of RP and BPP are arbitrary.

One-sided error: one witness is enough

Suppose an algorithm never errs on "no" inputs and, on "yes" inputs, says "yes" with probability at least pp. Run it kk times independently and answer "yes" if any run says "yes". A "no" input still always gets "no". A "yes" input gets "no" only if all kk runs fail:

Pr⁡[error]≤(1−p)k≤e−pk.\Pr[\text{error}] \le (1 - p)^k \le e^{-pk}.

To reach error δ\delta it is enough to take k=⌈ln⁡(1/δ)/p⌉k = \lceil \ln(1/\delta) / p \rceil. For RP (p=1/2p = 1/2), 30 runs give an error below 10−910^{-9}. The same reasoning gave Miller-Rabin its 4−s4^{-s} bound (Miller-Rabin: Error Bound and Cost), and it is why the RP constant 1/21/2 could be any constant, or even 1/q(n)1/q(n) for a polynomial qq: k=q(n)ln⁡(1/δ)k = q(n) \ln(1/\delta) runs restore any desired error.

Two-sided error: take a majority vote

If the algorithm can err in both directions, a single "yes" proves nothing. Instead, run it kk times (kk odd) and output the majority answer. Let each run be correct with probability 12+γ\frac{1}{2} + \gamma for some γ>0\gamma > 0, independently. The majority is wrong only if at most (k−1)/2(k - 1)/2 runs are correct, and the number of correct runs is binomial. Hoeffding's inequality, proved in Hoeffding's Inequality, bounds that tail:

Pr⁡[majority wrong]≤e−2γ2k.\Pr[\text{majority wrong}] \le e^{-2\gamma^2 k}.

So k=⌈ln⁡(1/δ)/(2γ2)⌉k = \lceil \ln(1/\delta) / (2\gamma^2) \rceil runs push the error below δ\delta. With γ=1/6\gamma = 1/6 (success 2/32/3, the BPP constant) that is 18ln⁡(1/δ)18 \ln(1/\delta) runs. Notice what is required: the advantage γ\gamma must be bounded away from 0. If it were 2−n2^{-n}, the number of runs would be exponential, which is why BPP insists on a constant gap (or at least an inverse-polynomial one).

The program computes the exact error of the majority vote from the binomial distribution and compares it with the bound.

python · try it yourself
from math import comb, exp

def majority_error(q, k):
    """Exact probability that at most (k-1)/2 of k runs are correct, each correct with probability q."""
    return sum(comb(k, j) * q ** j * (1 - q) ** (k - j) for j in range((k - 1) // 2 + 1))

q = 2 / 3
gamma = q - 0.5
print(f"single run correct with probability {q:.4f}")
print("  k   exact majority error   bound e^(-2 gamma^2 k)   one-sided (1/3)^k")
for k in [1, 5, 11, 21, 41, 81, 161]:
    print(f"{k:3}   {majority_error(q, k):20.3e}   {exp(-2 * gamma ** 2 * k):22.3e}   {(1 - q) ** k:17.3e}")
single run correct with probability 0.6667
  k   exact majority error   bound e^(-2 gamma^2 k)   one-sided (1/3)^k
  1              3.333e-01                9.460e-01           3.333e-01
  5              2.099e-01                7.575e-01           4.115e-03
 11              1.221e-01                5.427e-01           5.645e-06
 21              5.572e-02                3.114e-01           9.560e-11
 41              1.351e-02                1.025e-01           2.742e-20
 81              9.728e-04                1.111e-02           2.255e-39
161              6.459e-06                1.305e-04           1.526e-77

The bound is loose by a constant factor in the exponent, yet it captures the right behaviour: exponential decay in kk. The last column shows how much faster one-sided error falls, since there a single success settles the question.

A noisy test, amplified

The program below simulates a two-sided test that is right with probability 0.60.6 on every input and amplifies it by a majority vote of kk runs. Every vote uses fresh random numbers; reusing the same random bits for all kk runs would just repeat the same answer kk times and gain nothing.

text
AMPLIFY(x, k)                     // k odd
0  yes = 0
1  for j = 0 to k - 1
2      if NOISY-TEST(x) == "yes"  // fresh random bits for every run
3          yes = yes + 1
4  if yes > k / 2 return "yes" else return "no"
python · try it yourself
import random
from math import exp

def noisy_test(truth, rng):
    return truth if rng.random() < 0.6 else (not truth)

def amplify(truth, k, rng):
    yes = sum(noisy_test(truth, rng) for _ in range(k))
    return yes > k / 2

rng = random.Random(11)
trials = 4000
print("  k   measured error   Hoeffding bound")
for k in [1, 11, 31, 61, 101]:
    wrong = sum(amplify(True, k, rng) is not True for _ in range(trials))
    print(f"{k:3}   {wrong / trials:14.4f}   {exp(-2 * 0.1 ** 2 * k):15.4f}")
  k   measured error   Hoeffding bound
  1           0.3965            0.9802
 11           0.2455            0.8025
 31           0.1348            0.5379
 61           0.0578            0.2952
101           0.0185            0.1327

In C++

The same majority vote with a fixed-seed std::mt19937; the coin is rng() % 10 < 6. The generator differs from Python's, so the measured errors differ a little from the Python run.

cpp · try it yourself
#include <cmath>
#include <cstdio>
#include <random>

std::mt19937 rng(11);

bool noisy_test(bool truth) { return (rng() % 10 < 6) ? truth : !truth; }

bool amplify(bool truth, int k) {
    int yes = 0;
    for (int j = 0; j < k; ++j) yes += noisy_test(truth);
    return 2 * yes > k;
}

int main() {
    const int trials = 4000;
    std::printf("  k   measured error   Hoeffding bound\n");
    for (int k : {1, 11, 31, 61, 101}) {
        int wrong = 0;
        for (int t = 0; t < trials; ++t) wrong += !amplify(true, k);
        std::printf("%3d   %14.4f   %15.4f\n", k, double(wrong) / trials, std::exp(-2 * 0.01 * k));
    }
}
  k   measured error   Hoeffding bound
  1           0.3995            0.9802
 11           0.2447            0.8025
 31           0.1172            0.5379
 61           0.0540            0.2952
101           0.0240            0.1327

The median trick for estimates

Many randomized algorithms do not decide but estimate a number μ\mu: a count, a fraction, a norm. Typically a basic estimator YY is unbiased and has small variance, and Chebyshev's inequality gives

Pr⁡[∣Y−μ∣>ε]≤Var⁡[Y]ε2≤14\Pr\bigl[\lvert Y - \mu \rvert > \varepsilon \bigr] \le \frac{\operatorname{Var}[Y]}{\varepsilon^2} \le \frac{1}{4}

once enough samples are averaged into YY. To reach a failure probability δ\delta instead of 1/41/4, averaging more samples would cost a factor 1/δ1/\delta (Chebyshev only gives polynomial decay). The median trick costs a factor ln⁡(1/δ)\ln(1/\delta) instead: compute kk independent copies Y1,…,YkY_1, \ldots, Y_k and output their median. The median lies outside [μ−ε,μ+ε][\mu - \varepsilon, \mu + \varepsilon] only if at least half of the copies do, and each copy does so with probability at most 1/41/4. That is a majority vote with γ=1/4\gamma = 1/4, so

Pr⁡[∣median⁡−μ∣>ε]≤e−2(1/4)2k=e−k/8,\Pr\bigl[\lvert \operatorname{median} - \mu \rvert > \varepsilon\bigr] \le e^{-2(1/4)^2 k} = e^{-k/8},

and k=⌈8ln⁡(1/δ)⌉k = \lceil 8 \ln(1/\delta) \rceil copies suffice. Streaming algorithms such as the AMS sketch use exactly this "average, then take the median" pattern (Streaming, Sketching & Sublinear Algorithms).

The experiment estimates the fraction f=0.3f = 0.3 of marked items in a large collection by sampling. With ss samples, Var⁡[Y]=f(1−f)/s\operatorname{Var}[Y] = f(1-f)/s, so Chebyshev guarantees failure at most 1/41/4 for accuracy ε\varepsilon once s≥4f(1−f)/ε2s \ge 4f(1-f)/\varepsilon^2. To see the median at work, the program uses a deliberately weak estimator, s=50s = 50 samples and ε=0.08\varepsilon = 0.08, which fails about one time in five on its own (below 1/41/4, as the trick requires).

python · try it yourself
import random
from math import exp

f_true = 0.3
def estimate(rng, s=50):
    return sum(rng.random() < f_true for _ in range(s)) / s

rng = random.Random(2)
trials, eps = 300, 0.08
print("  k   failure rate of the median   bound e^(-k/8)")
for k in [1, 5, 9, 17]:
    fails = 0
    for _ in range(trials):
        ys = sorted(estimate(rng) for _ in range(k))
        if abs(ys[k // 2] - f_true) > eps:
            fails += 1
    print(f"{k:3}   {fails / trials:27.4f}   {min(1, exp(-k / 8)):14.4f}")
  k   failure rate of the median   bound e^(-k/8)
  1                        0.2033           0.8825
  5                        0.0300           0.5353
  9                        0.0067           0.3247
 17                        0.0000           0.1194

The bound e−k/8e^{-k/8} is pessimistic because it only uses "each copy fails with probability at most 1/41/4"; the measured failure rate falls much faster. The point of the trick is that it needs nothing more than that weak guarantee, which Chebyshev provides for every estimator with bounded variance.

In practice

  • Independence is the whole point. The repetitions must use independent random bits. Seeding each run with the same seed, or with predictable consecutive seeds of a poor generator, silently voids the analysis.
  • Random bits cost something. Plain repetition with kk runs uses kk times as many random bits. Walks on expander graphs achieve the same exponential decay with only O(k)O(k) extra bits beyond one run, a topic of Spectral Graph Theory.
  • Error below hardware failure. An error of 2−1002^{-100} is smaller than the probability that a cosmic ray flips a bit during the computation, so amplified Monte Carlo answers are, in practice, as trustworthy as deterministic ones.

Test yourself

An RP algorithm accepts "yes" inputs with probability at least 1/21/2 and never accepts "no" inputs. How many independent runs make the error at most 2−402^{-40}?

  1. 20
  2. 40
  3. 80
  4. 1600

A two-sided algorithm is correct with probability 0.550.55. Roughly how does the error of a majority vote over kk runs behave?

  1. It stays at 0.450.45
  2. It decays like e−2(0.05)2ke^{-2(0.05)^2 k}
  3. It decays like 1/k1/k
  4. It grows with kk

Why does the median trick output the median of kk estimates instead of their mean?

  1. The mean is biased
  2. The median is wrong only if half of the estimates are bad, which is exponentially unlikely, while one wild estimate can spoil the mean
  3. The median is cheaper to compute
  4. The mean needs more memory

What goes wrong if all kk repetitions of a Monte Carlo test reuse the same random seed?

  1. Nothing, the vote is still a majority
  2. All runs give the same answer, so the error stays that of one run
  3. The error doubles
  4. The running time becomes infinite