Sub topic 9
Common Bugs: Off-by-One Ranges, Modulo Bias, and Seeding
This chapter assumes you know Algorithm R, the k/n correctness argument, and basic use of Python's random module. The bugs covered here don't crash anything. The code runs and returns k items, but the sample is quietly non-uniform, and only a statistical check will show it.
| Bug | Symptom | Fix |
|---|---|---|
| Off-by-one in the slot range | Later items are over-represented | Draw `j` from `0..i` inclusive (0-based `i`) |
| Modulo bias | Low slot indices are chosen slightly more often | Use `randrange` or rejection sampling |
| Shared or repeated seeds | Partitions or runs make correlated choices | Use one seeded generator per independent stream |
Off-by-One in the Random Range
With 0-based indexing, item i is the (i+1)-th item seen, so it must enter the reservoir with probability k/(i+1). That requires j drawn uniformly from 0..i inclusive. Python makes this easy to get wrong because randint(a, b) includes b while randrange(a, b) excludes it.
import random
from collections import Counter
def buggy_reservoir(stream, k, rng):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i - 1) # BUG: should be randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
rng = random.Random(42)
trials = 100_000
counts = Counter()
for _ in range(trials):
counts.update(buggy_reservoir(range(10), 3, rng))
for x in range(10):
print(x, round(counts[x] / trials, 3)) # uniform would be 0.3 eachWhen i == k, the range 0..k-1 always gives j < k, so item k always enters the reservoir. Every later item enters with probability k/i instead of k/(i+1). Run the code and you will see the early items fall well below 0.3 while the last few rise above it. The same mistake can come from mixing a 1-based counter (enumerate(stream, start=1)) with randint(0, i). Choose one convention and derive the range from it.
Modulo Bias
Many languages give you a raw generator that returns integers in [0, 2^b). Writing raw() % m is biased whenever m does not divide 2^b. Take an 8-bit source and m = 10. The 256 raw values map to residues 0–5 twenty-six times each and to residues 6–9 only twenty-five times each. In reservoir sampling, m grows to n, so the bias grows as n approaches the generator's range.
Python's randrange and randint already use rejection sampling internally. If you port the algorithm to another language, or build on raw bits yourself, reject the values in the incomplete top block:
import random
def unbiased_below(m, rng, bits=32):
"""Uniform integer in [0, m) from b-bit raw draws; requires 1 <= m <= 2**bits."""
span = 1 << bits
limit = span - (span % m) # largest multiple of m that fits in the span
while True:
x = rng.getrandbits(bits)
if x < limit:
return x % m
rng = random.Random(7)
print(unbiased_below(10, rng))A related pitfall is int(rng.random() * m). A double has only 53 bits of precision, so for very large m some integers can never be produced. Prefer an integer-based method.
Seeding Mistakes
Seeds cause trouble in three common ways:
- Reseeding inside the loop, for example calling
random.seed(time.time())on every item. Consecutive seeds within the same clock tick repeat draws, and the outputs stop being independent. - Identical seeds across workers. If every partition seeds with
42, the workers make the same replacement decisions at the same positions, which correlates the samples you later combine. - Relying on global state. Other libraries can consume or reset the module-level generator and make your runs irreproducible.
Seed once, keep a dedicated generator for each independent stream, and pass it into the sampler:
import random
def make_worker_rngs(base_seed, num_workers):
# Distinct, reproducible seeds per worker; string seeds are hashed by Python
return [random.Random(f"{base_seed}-worker-{w}") for w in range(num_workers)]
rngs = make_worker_rngs(2026, 4)
print([r.randrange(100) for r in rngs])Exercise
A colleague writes Algorithm R with for i, item in enumerate(stream, start=1), uses if i <= k to fill the reservoir, and then draws j = rng.randint(0, i) with if j < k: reservoir[j] = item. What is wrong, and what is the minimal fix?
Show answer
With a 1-based i, item i should be kept with probability k/i. randint(0, i) has i+1 outcomes, so the code keeps it with probability k/(i+1), which under-represents later items. Replace the draw with j = rng.randrange(i) (or randint(0, i - 1)), which gives i outcomes.
Exercise
An 8-bit generator is used as raw % 100 to pick a slot. Which residues are more likely, and by what ratio?
Show answer
256 = 2·100 + 56, so residues 0–55 each occur 3 times and residues 56–99 occur 2 times. The low residues are 1.5 times as likely.