Sub topic 10
Algorithm L: Skipping Ahead with Geometric Jumps
This chapter assumes you have worked through Algorithm R, its induction proof, and the cost analysis from earlier chapters. You should be comfortable with the geometric distribution and with reading Python that uses iterators and itertools.islice.
Algorithm R calls the random number generator once for every item in the stream. For a stream of a billion items and a reservoir of 100, that is a billion random draws, and almost all of them end with "do nothing." Algorithm L, published by Kim-Hung Li in 1994, skips that wasted work. It computes in advance how many items will be rejected before the next replacement, jumps over them, and only draws random numbers when the reservoir actually changes.
The Waste in Algorithm R
The cost analysis chapter showed that item i (1-based, i > k) enters the reservoir with probability k/i. The expected number of replacements over a stream of length n is therefore:
- the sum of k/i for i from k+1 to n, which is about k · ln(n/k).
For n = 10^9 and k = 100, that is roughly 100 · ln(10^7) ≈ 1,600 replacements. Algorithm R still makes about 10^9 random draws to find those 1,600 events. If the stream is cheap to read, random number generation becomes the bottleneck.
Algorithm L's aim is to make the number of random draws proportional to the number of replacements, not to n.
Reframing Algorithm R with Random Keys
Algorithm L is easiest to understand through the random-keys view, which a later chapter covers in full. Picture each item receiving an independent uniform key in (0, 1). A uniform sample of size k is the set of k items with the smallest keys.
Let W be the largest key currently in the reservoir. That is the k-th smallest key seen so far. A new item enters the reservoir exactly when its key is less than W. When it enters, it evicts the item whose key was W.
From this view come three facts. Together they make up the whole algorithm.
- Initial threshold. After the first k items, W is the maximum of k independent uniforms. Its distribution is that of U^(1/k) for a single uniform U, because P(max ≤ x) = x^k.
- Gap to the next acceptance. Each later item is accepted independently with probability W. The number of rejected items before the next acceptance is geometric: P(skip = s) = (1 − W)^s · W. You can sample it by inversion as floor(ln U / ln(1 − W)).
- Threshold after a replacement. Once a new item is accepted, the k keys in the reservoir are all uniform on (0, W) and independent. The new maximum is therefore W · U^(1/k).
The algorithm never has to store the keys. It only tracks W.
The Algorithm
Here is the implementation:
import math
import random
from itertools import islice
_END = object()
def _open_unit(rng):
u = 0.0
while u == 0.0:
u = rng.random() # value in (0, 1)
return u
def algorithm_l(stream, k, rng=random):
it = iter(stream)
reservoir = list(islice(it, k))
if len(reservoir) < k:
return reservoir
w = math.exp(math.log(_open_unit(rng)) / k)
while True:
skip = math.floor(math.log(_open_unit(rng)) / math.log(1 - w))
nxt = next(islice(it, skip, skip + 1), _END)
if nxt is _END:
return reservoir
reservoir[rng.randrange(k)] = nxt
w *= math.exp(math.log(_open_unit(rng)) / k)Some details to notice:
math.exp(math.log(u) / k)computes u^(1/k). It is equivalent tou ** (1/k), and the log form matches the original paper._open_unitrejects 0.0. Python'srandom()returns values in [0, 1), andmath.log(0.0)raisesValueError.islice(it, skip, skip + 1)dropsskipitems and yields the next one. Becauseitis a shared iterator, the skipped items are consumed for good.- The sentinel
_ENDseparates "the stream ended" from a legitimate item such asNone.
What the Skip Actually Saves
The islice call still pulls every skipped item through the iterator. Algorithm L does not read fewer items from a Python generator. It makes fewer random draws and runs less Python bytecode per item, because islice advances the iterator in C.
The large savings come when the source can seek. Examples are a file of fixed-width records, an array in memory, or a storage layer that can skip ahead by offset. In those cases a skip of s items becomes one seek instead of s reads.
| Property | Algorithm R | Algorithm L |
|---|---|---|
| Random draws | n − k | about 3 per replacement, so O(k(1 + log(n/k))) |
| Items read from an iterator | n | n (skipped items are still consumed) |
| Items read from a seekable source | n | O(k(1 + log(n/k))) seeks |
| Memory | O(k) | O(k) |
| Floating-point math | none (integer `randint`) | `log`, `exp` per replacement |
| Output distribution | uniform | uniform |
Measuring the Random-Number Savings
The script below counts calls to the generator for both algorithms. It includes Algorithm R and the Algorithm L definitions from above, so you can run it as one file.
import math
import random
from itertools import islice
_END = object()
def _open_unit(rng):
u = 0.0
while u == 0.0:
u = rng.random()
return u
def algorithm_l(stream, k, rng=random):
it = iter(stream)
reservoir = list(islice(it, k))
if len(reservoir) < k:
return reservoir
w = math.exp(math.log(_open_unit(rng)) / k)
while True:
skip = math.floor(math.log(_open_unit(rng)) / math.log(1 - w))
nxt = next(islice(it, skip, skip + 1), _END)
if nxt is _END:
return reservoir
reservoir[rng.randrange(k)] = nxt
w *= math.exp(math.log(_open_unit(rng)) / k)
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 CountingRandom(random.Random):
def __init__(self, seed=None):
super().__init__(seed)
self.calls = 0
def random(self):
self.calls += 1
return super().random()
def randrange(self, *args, **kwargs):
self.calls += 1
return super().randrange(*args, **kwargs)
n, k = 1_000_000, 10
rng_r = CountingRandom(1)
reservoir_sample(range(n), k, rng_r)
rng_l = CountingRandom(1)
algorithm_l(range(n), k, rng_l)
print("Algorithm R draws:", rng_r.calls)
print("Algorithm L draws:", rng_l.calls)
print("3*k*ln(n/k) estimate:", round(3 * k * math.log(n / k)))Algorithm R reports 999,990 draws. Algorithm L reports a few hundred, close to the estimate of about 345, and the exact count changes with the seed. (randint delegates to randrange, so each draw in Algorithm R is counted once.)
You should also confirm that Algorithm L is still uniform. Reuse the frequency check from the testing chapter, calling algorithm_l(range(10), 3) instead of reservoir_sample. Every item should appear in close to 30% of trials.
Numerical Gotchas
Algorithm L replaces integer comparisons with floating-point math, which brings failure modes Algorithm R does not have.
Loss of precision when W is close to 1
Right after the reservoir fills, W can be very close to 1, especially for small k. Then 1 - w loses most of its significant digits. The expression math.log1p(-w) computes ln(1 − W) more accurately and can be swapped in without other changes:
import math
w = 1 - 1e-17 # rounds to 1.0 in double precision
print(1 - w) # 0.0
w = 0.999999999
print(math.log(1 - w), math.log1p(-w)) # nearly equal; log1p is more accurateIf W rounds to exactly 1.0, math.log(1 - w) raises ValueError for log(0). That happens only when U^(1/k) rounds to 1, which requires a very large k or a U extremely close to 1. A defensive implementation clamps W below 1 or treats that case as skip = 0.
Division by zero when W is tiny
Late in a very long stream, W shrinks toward 0. If W is smaller than about 1.1 × 10^-16, then 1 - w rounds to 1.0, math.log(1.0) is 0.0, and the division raises ZeroDivisionError. math.log1p(-w) avoids this until W underflows below about 10^-308, which no real stream reaches. In that regime the skip is so large that the stream will end first.
Huge skips
When W is small, skip can be a very large integer. Python's integers handle this, and islice simply runs to the end of the stream. In languages with fixed-width integers, convert the float to a 64-bit integer carefully. A value above 2^63 overflows, so clamp it to the maximum.
When to Prefer Algorithm L
Choose Algorithm L when:
- the source supports cheap skipping by offset, or
- random draws are expensive compared with reading items, for example with a cryptographic generator, or
- n is much larger than k, so that k · ln(n/k) is far below n.
Stay with Algorithm R when:
- you need exact, integer-only arithmetic that reproduces across platforms,
- you must touch every item anyway, for counting, filtering, or computing other statistics in the same pass, or
- the stream is short or k is close to n, so the savings are small.
Both algorithms give identically distributed samples. Seeded with the same value, though, they produce different samples, because they consume the generator in different orders. Do not swap one for the other in a pipeline that depends on reproducible output.
Exercise
Right after the reservoir fills, W = 0.5 and k = 4. What is the expected number of items skipped before the next replacement, and what is the expected value of W after that replacement? (For a uniform U, E[U^(1/k)] = k/(k+1).)
Show answer
The skip is geometric with success probability W = 0.5, so its expected value is (1 − W)/W = 1 item. After the replacement, W becomes 0.5 · U^(1/4), with expected value 0.5 · 4/5 = 0.4.
Exercise
A colleague "optimizes" Algorithm L by always overwriting slot 0 instead of a random slot, arguing that the skip computation already handles the randomness. Is the output still a uniform sample? Explain.
Show answer
No. Slots 1 to k−1 would never change, so the first k−1 items of the stream would always be in the sample, with probability 1 instead of k/n. The random slot stands in for evicting the item with the largest key, which is equally likely to be in any slot. Without it, the eviction is no longer uniform across the reservoir.
Exercise
Change algorithm_l so it uses math.log1p for ln(1 − W). Then run the uniformity check with k = 3 on range(10) for 100,000 trials. What frequencies do you expect, and why should this change not affect them?
Show answer
Replace math.log(1 - w) with math.log1p(-w). Each item should appear in about 0.3 of trials, within roughly ±0.005. The value log1p(-w) is the same quantity, ln(1 − W), computed with less rounding error, so the distribution does not change. The only difference is better numerical behavior when W is near 0 or 1.