Sub topic 3
Why Storing Everything or Using a Fixed Probability Fails
This chapter assumes you can read basic Python, know what a uniform distribution and independent events are, and are comfortable with Big-O notation. It looks at the obvious ways to sample from a stream and shows where each one breaks the streaming constraints: a single pass, an unknown length, and bounded memory.
Approach 1: Store Everything, Then Sample
The simplest idea is to collect the whole stream into a list and call random.sample at the end.
import random
def store_then_sample(stream, k, rng=random):
items = list(stream) # holds all n items in memory
return rng.sample(items, k)The output is a correct uniform sample. The cost is O(n) memory. If the stream is a day of web logs or a sensor feed that never stops, n is unbounded and the list eventually exhausts RAM. The approach also gives you nothing until the stream ends, so you cannot ask "what does my sample look like so far?"
Approach 2: Count First, Then Sample
If you knew n, you could pick k random positions in advance and keep the items at those positions. To learn n, you make one pass to count and a second pass to collect. That needs O(k) memory, but it reads the data twice. A network socket, a generator, or a message queue cannot be replayed. Even for files on disk, a second full scan doubles the I/O.
Approach 3: Keep Each Item With a Fixed Probability p
This is Bernoulli sampling: keep each item independently with probability p. It uses one pass and no stored history.
import random
def bernoulli_sample(stream, p, rng=random):
return [x for x in stream if rng.random() < p]
random.seed(1)
sizes = [len(bernoulli_sample(range(1000), 0.01)) for _ in range(10)]
print(sizes) # sizes scatter around 10 instead of being exactly 10There are two problems. First, the sample size follows a binomial distribution with mean np, so you cannot promise exactly k items. Second, to aim for k items you need p = k/n, and n is the quantity you don't know. If you guess too high, memory grows without bound. If you guess too low, you end up with too few items.
Approach 4: Replace the Kept Item With a Fixed Probability
A common next attempt keeps one item and replaces it with each new item at a constant probability q. The space is bounded, but the result is heavily biased toward recent items.
import random
from collections import Counter
def fixed_replace(stream, q, rng=random):
chosen = None
for i, item in enumerate(stream):
if i == 0 or rng.random() < q:
chosen = item
return chosen
trials = 100_000
counts = Counter(fixed_replace(range(10), 0.5) for _ in range(trials))
for x in range(10):
print(x, counts[x] / trials)Item 9 wins about half the time. Item 0 must survive nine coin flips, so it wins with probability 0.5⁹ ≈ 0.002. A uniform sampler would give each item 0.1.
Summary of the Failures
| Approach | Passes | Memory | Exactly k items | Uniform | What breaks |
|---|---|---|---|---|---|
| Store everything | 1 | O(n) | Yes | Yes | Unbounded memory |
| Count, then sample | 2 | O(k) | Yes | Yes | Needs a replayable stream |
| Fixed probability p | 1 | O(pn) | No | Yes | Needs n to set p |
| Fixed replacement q | 1 | O(1) | Yes | No | Favors late items |
The fourth row points to the fix. Replacement is the right mechanism, but the probability cannot stay constant. It has to shrink as the stream grows, and the next chapter works out exactly how.
Exercise
Using fixed replacement with q = 0.5 on a stream of n items, what is the probability that the first item is the one returned? For n = 20, how does that compare with the uniform target?
Show answer
The first item must survive n − 1 replacement chances, so the probability is 0.5^(n−1). For n = 20 that is 0.5^19 ≈ 1.9 × 10⁻⁶, against a uniform target of 1/20 = 0.05, which makes it about 26,000 times too unlikely.
Exercise
A Bernoulli sampler with p = 0.01 runs on a stream of 1,000 items. What are the mean and standard deviation of the sample size?
Show answer
The sample size is Binomial(1000, 0.01). The mean is np = 10, and the standard deviation is sqrt(np(1 − p)) = sqrt(9.9) ≈ 3.15, so sizes from about 4 to 16 are routine.