## Reservoir Sampling

### January 31, 2014

If you want to choose a sample of *k* out of *n* items, and the *n* items are stored in an array, choosing the sample is easy: just generate *k* random numbers from 0 to *n*−1, without duplicates, and look up the associated array items. But that’s harder to do if the items are stored in a list, because indexing into a list is O(*n*) instead of O(1), and it’s impossible if the list is too large to fit in memory. The Standard Prelude includes a function that works when *k* = 1, but in the general case we must use a streaming algorithm called reservoir sampling.

The algorithm creates an array of length *k*, the reservoir, and initializes it with the first *k* elements of the input list. Then the remaining *n* − *k* elements of list are each considered, one by one, in order. When the *i*th element of the input list is reached, a random integer *j* less than *i* is generated; if *j* < *k*, the *j*th element of the reservoir array is replaced by the *i*th element of the list. When all elements of the list have been considered, the items that remain in the reservoir array are returned as the *k* randomly-selected elements of the input list.

Your task is to write a program that performs reservoir sampling. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

In Python. Note that it is important to choose a random number inclusive i. Otherwise the first k items in the sequence will be undersampled. What is interesting about this form of reservir sampling is that you do not have to know the number of items in advance. On the downside, it is slow, as you need a random sample for every item.

Fun! Python or something. (Same as Paul’s but different.)

Some test results:

100-sampling [0, 1, ..., 999] 1000 times:

population mean: 499.5

mean deviation from population mean: 0.027230000000000528

`2-sampling [3, 1, 4] 999 times:`

335 [4, 1]

328 [3, 1]

337 [3, 4]

In this paper various methods for reservoir sampling are given. The simplest is algorithm R and is the same as suggested above. Also 2 more algorithms are given, named X and Z. I give here implementations. Timings for k=10 (or 100) and N=10000000 are R: 13 sec, X: 2.4 sec and Z: 0.17 sec. (I left out the code for R, as that is the same as my last post.

There is an error in algorithm_Z of my last post. I corrected it and the full code including test code can be found at here. Timing for Z is now 0.35 sec.

In Guile Scheme.

Here’s a solution in Julia.