Sub topic 9
Drawing Unbiased Random Indices
The proof of uniformity in the previous chapter assumed one thing without checking it. At step i, the index j had to be drawn uniformly from 0 to i. If some values of j come up more often than others, the proof no longer holds and some permutations become more likely. This chapter covers how that assumption fails in real code and how to make it hold.
This chapter assumes you know the in-place Fisher-Yates loop, basic probability, and integer division and remainder (// and % in Python). The JavaScript example also assumes you have seen typed arrays.
Where the randomness actually comes from
Random number generators rarely hand you "an integer from 0 to i." They give you raw bits: a 32-bit or 64-bit word, a byte from the operating system, or a float in [0, 1) built from bits. Your shuffle has to turn those bits into an index in a range whose size changes on every iteration. The sizes run n, n - 1, and so on down to 2. Most of those sizes are not powers of two, and that mismatch is where bias gets in.
Modulo bias
The obvious conversion is x % m, where x is a raw random value and m is the size of the range you need. It is wrong whenever the number of possible raw values is not a multiple of m.
Take a tiny generator that produces 3 bits, so the values 0 to 7, and suppose you need a number in [0, 3). The raw values map like this:
| Raw value `x` | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| `x % 3` | 0 | 1 | 2 | 0 | 1 | 2 | 0 | 1 |
Outcomes 0 and 1 each have three raw values behind them, and outcome 2 has only two. The probabilities are 3/8, 3/8, and 2/8, not 1/3 each. Eight raw values cannot be split evenly into three groups. This is the same counting problem that breaks the naive shuffle: equally likely inputs cannot spread evenly over outputs whose count does not divide the number of inputs.
You can count this exactly instead of sampling it:
from collections import Counter
def modulo_counts(bits, m):
"""How many raw values map to each outcome of x % m."""
return Counter(x % m for x in range(2 ** bits))
print(modulo_counts(3, 3))
print(modulo_counts(8, 52))The first line prints Counter({0: 3, 1: 3, 2: 2}). The second shows a common real bug: taking one random byte modulo 52 to pick a card. Since 256 = 4 × 52 + 48, the outcomes 0 to 47 each get 5 raw values and 48 to 51 get only 4. The low cards are 25% more likely than the high ones.
How large the bias gets
If the source has R equally likely values, every outcome gets either R // m or R // m + 1 raw values. Exactly R % m outcomes get the extra one. The relative error is therefore about 1 / (R // m).
| Source | Range size `m` | Extra-weighted outcomes | Favoured outcomes are more likely by |
|---|---|---|---|
| 3 bits (R = 8) | 3 | 2 | 50% |
| 8 bits (R = 256) | 52 | 48 | 25% |
| 32 bits | 52 | 32 | about 0.0000012% |
| 32 bits | 3,221,225,472 | 1,073,741,824 | 100% (twice as likely) |
With a 32-bit source and a deck-sized range, the bias is far too small to show up in any test you could run. It is still not zero, though, and the last row shows that it gets huge when m is a sizeable fraction of R. A shuffle library cannot assume its callers will only pass small arrays, so the correct fix is to remove the bias rather than argue that it is small.
Rejection sampling
The fix is to throw away the raw values that cause the unevenness. Find the largest multiple of m that fits in the source range: limit = (R // m) * m. Accept a raw value x only if x < limit. If x is too large, draw again. The accepted values 0 to limit - 1 split into exactly R // m full groups of m, so x % m is now exactly uniform.
In the 3-bit example, limit = (8 // 3) * 3 = 6. The values 6 and 7 are rejected, and the remaining six values map to 0, 1, 2, 0, 1, 2. You can check this by enumerating every raw value:
from collections import Counter
def accepted_counts(bits, m):
R = 2 ** bits
limit = (R // m) * m
return Counter(x % m for x in range(R) if x < limit)
print(accepted_counts(3, 3)) # each outcome: 2
print(accepted_counts(8, 52)) # each outcome: 4Cost of rejecting
Each draw is rejected with probability (R % m) / R, which is always below m / R and always below 1/2. The worst case is m just above R / 2. There, nearly half the draws are rejected, but the expected number of draws is still under 2. For a 32-bit source and any realistic array size, rejections almost never happen, so the loop costs essentially nothing. The shuffle stays O(n) in expectation. Its running time is no longer strictly bounded, but the chance of needing k retries shrinks geometrically.
A JavaScript version with a cryptographic source
crypto.getRandomValues fills a typed array with random bits from the operating system. Browsers provide crypto as a global, and so does Node.js 19 and later. Here is a shuffle that draws every index through rejection sampling:
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, 6, 7, 8, 9, 10]));JavaScript numbers are 64-bit floats, so 2 ** 32 and limit are represented exactly. When n is a power of two, limit equals 2 ** 32 and nothing is ever rejected, which is correct.
The bit-mask variant
Another way to do it is to draw just enough bits to cover the range and reject anything outside it. CPython's random.randrange works this way internally:
import random
def rand_below(n):
"""Unbiased integer in [0, n) using the smallest number of bits."""
if n <= 0:
raise ValueError("n must be positive")
k = n.bit_length()
r = random.getrandbits(k)
while r >= n:
r = random.getrandbits(k)
return r
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = rand_below(i + 1)
items[i], items[j] = items[j], items[i]
return items
print(fisher_yates(list(range(10))))k bits cover [0, 2**k), and 2**k is less than 2n, so again fewer than half the draws are rejected. This method uses fewer random bits per index than drawing a full 32-bit word.
Floating-point traps
Many languages offer a float in [0, 1), and the common idiom is Math.floor(Math.random() * m). It has two problems.
- Residual bias. A float in
[0, 1)comes from a finite number of bits, usually 52 or 53. Multiplying and flooring maps those2**53possible values ontombuckets, which is modulo bias in different clothing. For smallmthe error is aroundm / 2**53and too small to detect, but it is not exactly uniform. - Rounding mistakes.
Math.round(Math.random() * (m - 1))is a common and much worse bug. The endpoints0andm - 1each get only half-width intervals, so they come up about half as often as the middle values. Always floor, and always multiply bymitself, notm - 1.
Decision guide
| Situation | Use |
|---|---|
| Standard library has a bounded-integer function | That function |
| Only raw bits or bytes available | Rejection sampling with `limit` or a bit mask |
| Range is a power of two | Mask or `%` directly; no bias is possible |
| Float in `[0, 1)` only, and exactness matters | Get integer bits instead; don't scale the float |
An unbiased index makes each single step of the shuffle fair. It does not make the whole shuffle fair if the generator behind it cannot reach every permutation in the first place. The next chapter covers that problem.
Exercise
A program picks one of 10 digits by taking a random byte (0–255) modulo 10. Which digits are favoured, and by how much? What limit should rejection sampling use?
Show answer
256 = 25 × 10 + 6, so digits 0–5 each have 26 raw values and digits 6–9 have 25. The favoured digits are 26/25 = 1.04 times as likely, a 4% bias. Rejection sampling uses limit = 25 × 10 = 250: accept bytes 0–249 and redraw on 250–255.
Exercise
Using randomBelow from the JavaScript example, what is the probability that a single draw is rejected when n = 2**31 + 1, and what is the expected number of draws?
Show answer
limit = floor(232 / (231 + 1)) × (231 + 1) = 231 + 1, so 231 − 1 of the 232 raw values are rejected, a probability just under 1/2. The number of draws is geometric with success probability just over 1/2, so the expected count is just under 2.
Exercise
Why does Math.round(Math.random() * 2) give 0, 1, 2 with probabilities about 1/4, 1/2, 1/4?
Show answer
The product is uniform on [0, 2). It rounds to 0 on [0, 0.5), to 1 on [0.5, 1.5), and to 2 on [1.5, 2). Those intervals have lengths 0.5, 1, and 0.5 out of 2, giving 1/4, 1/2, 1/4. Math.floor(Math.random() * 3) gives three intervals of equal width instead.