Sub topic 9
Drawing Unbiased Random Indices
This chapter assumes you have read the in-place Fisher-Yates shuffle and its proof of uniformity. You should also be comfortable with the % (remainder) operator. The proof assumes something quiet: each call that picks j returns every value in 0..i with exactly equal probability. If that step is even slightly skewed, the shuffle is skewed too, however correct the loop is.
Where random integers come from
Most random sources give you raw bits. A raw value is usually a 32-bit or 64-bit unsigned integer, uniform over 0..2**32 - 1 or 0..2**64 - 1. Fisher-Yates needs something else: a uniform integer in [0, n) for a different n at every step. Turning one into the other is where bias creeps in.
Modulo bias
The obvious conversion is x % n. That conversion is fair only when the size of the source range divides evenly by n. Here is a toy source with 8 equally likely values, mapped onto 3 outcomes:
from collections import Counter
counts = Counter(x % 3 for x in range(8))
print(counts) # Counter({0: 3, 1: 3, 2: 2})The values 0, 3 and 6 map to 0. The values 1, 4 and 7 map to 1. Only 2 and 5 map to 2. So outcomes 0 and 1 each have probability 3/8, and outcome 2 has 2/8. The values 6 and 7 form a partial "block" at the top of the range, and that partial block is what tilts the result.
With a 32-bit source the tilt is tiny for small n, but it is never zero unless n is a power of two. During a shuffle, n takes every value from 2 up to the array length. The bias therefore lands on most steps, and it grows as n approaches the size of the source range.
Rejection sampling
The fix is to throw away the incomplete top block. Compute the largest multiple of n that fits in the source range. Call it limit. Accept x only if x < limit, and otherwise draw again. Every accepted value falls into a complete block, so every remainder has the same number of preimages.
Here is the same idea in JavaScript, wired into Fisher-Yates. It uses crypto.getRandomValues, which is available in browsers and in Node.js 19 and later.
function randomBelow(n) {
// Returns an unbiased integer in [0, n) for 1 <= n <= 2**32.
const limit = Math.floor(2 ** 32 / n) * n;
const buf = new Uint32Array(1);
let x;
do {
crypto.getRandomValues(buf);
x = buf[0];
} while (x >= limit);
return x % n;
}
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = randomBelow(i + 1);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
console.log(shuffle([1, 2, 3, 4, 5]));At most half of the source range is ever rejected, so the expected number of draws per call is below 2. For small n it is almost exactly 1.
Common errors
| Mistake | Effect |
|---|---|
| `x % n` on raw bits | Small values of the result are slightly favored |
| Rejecting `x > limit` instead of `x >= limit` | The value `limit` itself is accepted and maps to 0, so 0 gets an extra preimage |
| Calling `randomBelow(i)` instead of `randomBelow(i + 1)` | `j` can never equal `i`, which turns the shuffle into Sattolo's algorithm |
In Python, random.randint and random.randrange already use rejection sampling internally. You only need to write this yourself when you start from raw bits or bytes.
Exercise
A source yields uniform values 0..9 (10 values). You need a uniform integer in [0, 4). What is limit, which raw values are rejected, and what is the probability that a single draw is rejected?
Show answer
limit = floor(10 / 4) * 4 = 8. The values 8 and 9 are rejected, so the rejection probability is 2/10 = 0.2. Each accepted remainder 0, 1, 2 and 3 then has exactly two preimages.
Exercise
Why does x % 8 on a 32-bit source need no rejection at all?
Show answer
232 is divisible by 8, so limit equals 232. No raw value is ever at or above limit, and every remainder has exactly 2**29 preimages.