Amplification by Repetition
A Monte Carlo algorithm that errs with probability sounds unreliable. It is not: run it a few dozen times with fresh random bits and combine the answers, and the error drops below . 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 and 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 . Run it 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 runs fail:
To reach error it is enough to take . For RP (), 30 runs give an error below . The same reasoning gave Miller-Rabin its bound (Miller-Rabin: Error Bound and Cost), and it is why the RP constant could be any constant, or even for a polynomial : 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 times ( odd) and output the majority answer. Let each run be correct with probability for some , independently. The majority is wrong only if at most runs are correct, and the number of correct runs is binomial. Hoeffding's inequality, proved in Hoeffding's Inequality, bounds that tail:
So runs push the error below . With (success , the BPP constant) that is runs. Notice what is required: the advantage must be bounded away from 0. If it were , 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.
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 . 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 on every input and amplifies it by a majority vote of runs. Every vote uses fresh random numbers; reusing the same random bits for all runs would just repeat the same answer times and gain nothing.
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"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.
#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 : a count, a fraction, a norm. Typically a basic estimator is unbiased and has small variance, and Chebyshev's inequality gives
once enough samples are averaged into . To reach a failure probability instead of , averaging more samples would cost a factor (Chebyshev only gives polynomial decay). The median trick costs a factor instead: compute independent copies and output their median. The median lies outside only if at least half of the copies do, and each copy does so with probability at most . That is a majority vote with , so
and 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 of marked items in a large collection by sampling. With samples, , so Chebyshev guarantees failure at most for accuracy once . To see the median at work, the program uses a deliberately weak estimator, samples and , which fails about one time in five on its own (below , as the trick requires).
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 is pessimistic because it only uses "each copy fails with probability at most "; 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 runs uses times as many random bits. Walks on expander graphs achieve the same exponential decay with only extra bits beyond one run, a topic of Spectral Graph Theory.
- Error below hardware failure. An error of 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 and never accepts "no" inputs. How many independent runs make the error at most ?
- 20
- 40
- 80
- 1600
A two-sided algorithm is correct with probability . Roughly how does the error of a majority vote over runs behave?
- It stays at
- It decays like
- It decays like
- It grows with
Why does the median trick output the median of estimates instead of their mean?
- The mean is biased
- The median is wrong only if half of the estimates are bad, which is exponentially unlikely, while one wild estimate can spoil the mean
- The median is cheaper to compute
- The mean needs more memory
What goes wrong if all repetitions of a Monte Carlo test reuse the same random seed?
- Nothing, the vote is still a majority
- All runs give the same answer, so the error stays that of one run
- The error doubles
- The running time becomes infinite