Sub topic 8
Checking Uniformity Empirically
A correctness proof tells you that Algorithm R is uniform. It does not tell you that your code is. A sampler can look reasonable and pass a quick eyeball check while carrying a bias that skews every downstream estimate. This chapter turns the k/n guarantee into tests you can run, explains how many trials you need, and shows which tests catch which bugs.
This chapter assumes you have read the Algorithm R implementation and the induction proof from earlier chapters. It also assumes you know binomial variance (p(1−p)/trials for a sample proportion), what a z-score is, and the basic idea of a chi-square goodness-of-fit test.
What "Uniform" Means When You Test It
The proof gives two different properties, and they need different tests:
| Property | Statement | Test |
|---|---|---|
| Marginal inclusion | Each item appears in the sample with probability k/n | Per-item frequency with z-scores |
| Subset uniformity | Each of the C(n, k) possible subsets is equally likely | Chi-square over all subsets |
Subset uniformity implies marginal inclusion. The reverse does not hold. A sampler can give every item probability k/n and still produce badly skewed subsets, which is why passing a frequency test alone is not enough.
Test 1: Per-Item Inclusion Frequencies
Run the sampler many times on range(n) and count how often each item appears. Each item's count is a binomial random variable with trials attempts and success probability p = k/n. Its observed frequency therefore has standard deviation sqrt(p(1−p)/trials). Dividing the deviation from p by that standard deviation gives a z-score, and a correct sampler should keep every |z| small.
import math
import random
from collections import Counter
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # inclusive: 0..i
if j < k:
reservoir[j] = item
return reservoir
def buggy_reservoir(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i - 1) # wrong upper bound
if j < k:
reservoir[j] = item
return reservoir
def inclusion_check(sampler, n, k, trials, seed=12345, z_limit=4.0):
rng = random.Random(seed)
counts = Counter()
for _ in range(trials):
sample = sampler(range(n), k, rng)
assert len(sample) == min(k, n)
assert len(set(sample)) == len(sample), "duplicate item in sample"
for x in sample:
counts[x] += 1
p = k / n
sd = math.sqrt(p * (1 - p) / trials)
worst = 0.0
for x in range(n):
freq = counts[x] / trials
z = (freq - p) / sd
worst = max(worst, abs(z))
print(f"item {x}: freq={freq:.4f} z={z:+.2f}")
print(f"worst |z| = {worst:.2f}")
return worst <= z_limit
print("correct:", inclusion_check(reservoir_sample, 10, 3, 100_000))
print("buggy: ", inclusion_check(buggy_reservoir, 10, 3, 100_000))With 100,000 trials and p = 0.3, the standard deviation of each frequency is about 0.00145. The correct sampler keeps every frequency within a few thousandths of 0.3, and the worst |z| is usually below 3.
The buggy version fails badly. Item 3 always enters the reservoir, because randint(0, 2) is always less than 3. Working through the survival probabilities shows that items 0–2 end with frequency 2/9 ≈ 0.222 and items 3–9 with 1/3 ≈ 0.333. Those are z-scores of roughly −50 and +23. The next chapter explains where bugs like this come from. What matters here is that the test catches it.
The function also asserts the sample's size and that it contains no duplicates. These checks cost almost nothing, and they catch a different kind of bug, such as code that appends when it should overwrite.
Choosing the Threshold and the Number of Trials
You check n z-scores at once, so a limit of 2 would fail a correct sampler often just by chance. A limit of 4 has a two-sided false-alarm probability of about 6×10⁻⁵ per item, which keeps the test from failing randomly even across dozens of items.
To pick a trial count, decide the smallest bias δ you want to detect. You need z_limit × sd ≤ δ, so:
trials ≥ z_limit² × p(1−p) / δ²
To detect a bias of 0.01 at p = 0.3 with z_limit = 4, you need 16 × 0.21 / 0.0001 = 33,600 trials. Halving δ quadruples the trials. Statistical tests can rule out large biases cheaply, but tiny ones get expensive.
Test 2: Chi-Square Over All Subsets
Here is a sampler that passes Test 1 and is still wrong. It picks a random starting position and returns k consecutive items, wrapping around at the end:
import random
def block_sampler(stream, k, rng=random):
items = list(stream)
s = rng.randrange(len(items))
return [items[(s + t) % len(items)] for t in range(k)]Each item lies in exactly k of the n possible blocks, so its inclusion probability is exactly k/n. But only n distinct subsets can ever appear, out of C(n, k). For n = 5 and k = 2, it can return {0, 1} but never {0, 2}.
To test the joint distribution, record each sample as a frozenset, which is a hashable set that ignores order, and compare the subset counts with the uniform expectation. Each trial now produces exactly one outcome from C(n, k) categories. That makes the counts a true multinomial, and Pearson's chi-square test applies directly with C(n, k) − 1 degrees of freedom.
import random
from collections import Counter
from itertools import combinations
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
def block_sampler(stream, k, rng=random):
items = list(stream)
s = rng.randrange(len(items))
return [items[(s + t) % len(items)] for t in range(k)]
def subset_chi_square(sampler, n, k, trials, seed=2024):
rng = random.Random(seed)
counts = Counter(frozenset(sampler(range(n), k, rng)) for _ in range(trials))
subsets = [frozenset(c) for c in combinations(range(n), k)]
unexpected = set(counts) - set(subsets)
assert not unexpected, f"invalid samples seen: {unexpected}"
expected = trials / len(subsets)
stat = sum((counts[s] - expected) ** 2 / expected for s in subsets)
return stat, len(subsets) - 1
CRITICAL_DF9_ALPHA_0001 = 27.88 # chi-square critical value, df = 9, alpha = 0.001
for name, sampler in [("reservoir", reservoir_sample), ("block", block_sampler)]:
stat, df = subset_chi_square(sampler, 5, 2, 50_000)
verdict = "pass" if stat < CRITICAL_DF9_ALPHA_0001 else "FAIL"
print(f"{name}: chi2={stat:.1f}, df={df}, {verdict}")For Algorithm R the statistic usually lands near its expected value of 9, the degrees of freedom. For the block sampler, five subsets get twice their expected count and five get zero, so the statistic equals the number of trials: 50,000. If you have SciPy, scipy.stats.chisquare returns a p-value for you. The hard-coded critical value keeps this example free of dependencies.
The chi-square approximation needs enough expected observations per cell. A common rule is at least 5, and more is better. C(n, k) grows quickly: C(20, 10) is 184,756. So this test only works for small n and k. That limit is acceptable, because the logic of Algorithm R does not change with size. Bugs that show up at n = 20 almost always show up at n = 5 too.
Test 3: Exact Enumeration, With No Statistics
For tiny inputs you can avoid randomness entirely. Algorithm R makes one call randint(0, i) for each i from k to n−1, and every sequence of results is equally likely. If you replace the RNG with a scripted object that replays a given sequence, you can run the sampler on every possible sequence and count the outcomes exactly.
import random
from collections import Counter
from itertools import product
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
class ScriptedRNG:
def __init__(self, values):
self.values = iter(values)
def randint(self, a, b):
v = next(self.values)
assert a <= v <= b, f"scripted value {v} outside [{a}, {b}]"
return v
def exact_subset_counts(n, k):
ranges = [range(0, i + 1) for i in range(k, n)]
counts = Counter()
for choices in product(*ranges):
sample = reservoir_sample(range(n), k, rng=ScriptedRNG(choices))
counts[frozenset(sample)] += 1
return counts
counts = exact_subset_counts(5, 2)
print(len(counts), sorted(set(counts.values()))) # 10 [6]For n = 5 and k = 2 there are 3 × 4 × 5 = 60 sequences. Each of the 10 subsets comes out exactly 6 times, which proves uniformity for this input with no sampling error. The test depends on the sampler's internal sequence of RNG calls, so it is tied to this implementation. If you change randint to randrange, the scripted RNG has to change too. Use it as a precise unit test alongside the statistical tests, which treat the sampler as a black box.
Edge Cases Worth Asserting
Statistical tests cover the main path. Add direct assertions for the boundaries:
- n < k: the sample should contain all n items, not crash or pad with
None. - n = k: the sample should be exactly the input set every time.
- Empty stream: return an empty list.
- k = 0: return an empty list without consuming RNG calls if possible.
- Generator input: pass a generator, not a list, to confirm the sampler makes only one pass.
- Duplicate values in the stream: test with
range(n)so items are distinct, becausefrozensetwould hide genuine duplicates from a stream like[1, 1, 2].
Exercise
You want to detect a bias of 0.005 in inclusion frequency for n = 100, k = 10, using a z-limit of 4. About how many trials do you need?
Show answer
p = 0.1, so p(1−p) = 0.09. trials ≥ 16 × 0.09 / 0.005² = 1.44 / 0.000025 = 57,600 trials.
Exercise
A sampler passes the per-item frequency test with every |z| below 1.5, but the subset chi-square test on n = 5, k = 2 gives a statistic of 4,000 with 50,000 trials. What does this tell you, and which earlier example behaves this way?
Show answer
The marginal inclusion probabilities are correct but the joint distribution over subsets is not uniform: some pairs come up too often and others too rarely or never. The block_sampler, which returns k consecutive items from a random start, behaves this way.
Exercise
Why is Pearson's chi-square test valid on subset counts but not directly on the per-item inclusion counts from Test 1?
Show answer
Each trial produces exactly one subset, so subset counts are multinomial and the standard chi-square applies. In Test 1, each trial adds k items at once. The per-item counts are negatively correlated and each has variance trials·p(1−p) rather than trials·p, so the usual statistic does not follow a chi-square distribution with n−1 degrees of freedom.