Sub topic 10
When the Random Generator Is Too Small
This chapter assumes you know the in-place Fisher-Yates shuffle and the n! count of orderings. It also assumes you have read the uniformity proof from earlier chapters. You should be comfortable reading Python that uses random.Random, sets, and big integers.
The uniformity proof made one quiet assumption: each call to the random-index function returns a truly independent, uniform value. Real programs get their values from a pseudo-random number generator (PRNG), and a PRNG is a deterministic machine. This chapter shows how that machine can limit which permutations your shuffle can ever produce, even when the shuffle code itself is perfect.
Why a deterministic generator caps the output
A PRNG holds an internal state, which is a fixed number of bits. Each time you ask for a number, it updates the state with a fixed rule and derives the output from it. The state fully determines every future output. If two runs start from the same state, they produce the same sequence of numbers.
Fisher-Yates is also deterministic once its random numbers are fixed. So the whole pipeline is a function:
- A seed sets the starting state.
- The starting state fixes the sequence of random indices.
- The sequence of indices fixes the resulting permutation.
A generator with k bits of state has at most 2^k distinct starting states. A shuffle that starts from a fresh state can therefore reach at most 2^k distinct permutations. If 2^k is smaller than n!, some permutations have probability zero. No change to the shuffle loop can fix that.
The binding limit is often the seed, not the state. A generator can carry thousands of bits of state, but if you seed it from a 32-bit number, only 2^32 starting states are ever used. Reachability is bounded by whichever is smaller: the state size or the number of distinct seeds you actually feed in.
Seeing the cap with a toy generator
The following program builds a deliberately tiny generator. It is a linear congruential generator with 8 bits of state, so it has 256 possible states. It shuffles 6 items, which have 6! = 720 orderings, once from every possible seed.
def make_lcg(seed):
state = seed & 0xFF # 8 bits of state: 256 possible values
def next_byte():
nonlocal state
state = (5 * state + 3) % 256 # full-period LCG modulo 256
return state
return next_byte
def toy_randbelow(next_byte, n):
# Maps 0..255 onto 0..n-1. Slightly biased, but bias is not the point here.
return next_byte() * n // 256
def shuffle_with(items, next_byte):
for i in range(len(items) - 1, 0, -1):
j = toy_randbelow(next_byte, i + 1)
items[i], items[j] = items[j], items[i]
return items
reachable = {
tuple(shuffle_with(list(range(6)), make_lcg(seed)))
for seed in range(256)
}
print(len(reachable), "of 720 permutations are reachable")The printed count can never exceed 256, because there are only 256 seeds. At least 464 of the 720 orderings never appear, however many times you run the program. A frequency test of the kind covered later in this tutorial would flag this quickly, since most cells of the table would stay at zero.
The same thing happens with a strong generator if you restrict the seeds:
import random
decks = set()
for seed in range(1000):
rng = random.Random(seed)
deck = list(range(52))
rng.shuffle(deck)
decks.add(tuple(deck))
print(len(decks), "distinct decks from 1000 seeds")Python's Mersenne Twister has 19,937 bits of state, but this program can only produce at most 1,000 decks. Out of roughly 8 × 10^67 possible decks, that is effectively none of them.
How many bits a permutation needs
To make every ordering of n items reachable, you need 2^k ≥ n!, which means k ≥ log2(n!). The following program computes this bound exactly using Python's big integers.
import math
def bits_needed(n):
"""Minimum whole bits of state so that 2**bits >= n!."""
return (math.factorial(n) - 1).bit_length()
def largest_n(bits):
"""Largest n whose n! orderings all fit in 2**bits states."""
n = 1
while math.factorial(n + 1) <= 2 ** bits:
n += 1
return n
for n in (10, 20, 52, 100, 1000):
print(f"{n:>5} items need {bits_needed(n):>5} bits")
for bits in (32, 64, 128, 256):
print(f"{bits:>4} bits cover every ordering of up to {largest_n(bits)} items")The results are worth remembering:
| Items (n) | log2(n!) | Minimum bits |
|---|---|---|
| 10 | 21.8 | 22 |
| 20 | 61.1 | 62 |
| 52 (a card deck) | 225.6 | 226 |
| 100 | 524.8 | 525 |
| State or seed bits | Largest n fully covered |
|---|---|
| 32 | 12 |
| 64 | 20 |
| 128 | 34 |
| 256 | 57 |
A 64-bit seed cannot even cover a 21-item list. A standard deck of cards needs more than 225 bits. This is why seeding a shuffle from a single 32-bit or 64-bit integer is a problem for anything beyond toy sizes.
Period versus state
A generator's period is how many outputs it produces before the sequence repeats. The period can be no larger than 2^k, and good generators come close to that. Python's Mersenne Twister has period 2^19937 − 1.
When you shuffle repeatedly from one long-running generator, each shuffle starts from wherever the stream currently is. The number of distinct starting points is bounded by the period. The Python documentation for random.shuffle notes that 2,080 is the largest sequence length whose permutations can all fit within the Mersenne Twister's period. Beyond that length, most permutations of the list can never be generated.
In practice, a missing permutation matters for 2,080 items much less than for 52 items. Nobody can enumerate 2080! outcomes or tell that one is absent. The cap becomes a real failure when it is small enough to search. That happens with small seeds, guessable seeds, or a weak generator used for something an adversary cares about.
When a small seed becomes an attack
In 1999, researchers at Reliable Software Technologies examined an online poker application. They found that it shuffled with a generator seeded from the number of milliseconds since midnight. That gives about 86.4 million seeds, roughly 2^26, against 52! decks. Once an attacker had seen a few cards and synchronized with the server's clock, they could try the plausible seeds and recover the entire deck in real time. The same code also used a biased swap-with-any-index shuffle, but the seed was the bigger problem.
The lesson applies to any seed taken from the clock, a process ID, or a counter. These values have little real entropy, meaning unpredictability measured in bits. An attacker who knows roughly when the shuffle ran can narrow the search to a tiny window. Even a generator with a huge state is only as unpredictable as its seed. Mersenne Twister has a further weakness: an observer who sees 624 consecutive 32-bit outputs can reconstruct its full state and predict everything that follows.
Choosing and seeding a generator
Match the generator to what the shuffle protects.
| Use case | Recommended approach | Why |
|---|---|---|
| Unit tests, reproducible simulations | `random.Random(fixed_seed)` | Repeatable output; reachability rarely matters |
| Games, playlists, statistical sampling | `random.shuffle` with default seeding | Large state, seeded from the OS at startup |
| Gambling, lotteries, security tokens, anything adversarial | `random.SystemRandom().shuffle` or the `secrets` module | OS randomness; no recoverable internal state |
| Other languages, adversarial use | The platform's cryptographic source, such as `crypto.getRandomValues` | Same reasoning |
When Python's random module is not seeded explicitly, it seeds itself from the operating system's randomness source. That seed is far larger than 226 bits, so for ordinary use the default is fine. The common mistake is overriding it with something weaker:
import random
import time
deck = list(range(52))
# Weak: the seed is guessable and the seed space is small.
random.seed(int(time.time()))
random.shuffle(deck)
# Fine for non-adversarial use: default OS-based seeding.
rng = random.Random()
rng.shuffle(deck)
# Required when someone benefits from predicting the order.
secure = random.SystemRandom()
secure.shuffle(deck)Checklist
- Compute log2(n!) for your largest list and compare it with your seed's real entropy, not with the generator's advertised state size.
- Never seed from the clock, a PID, or a small counter when the outcome has value to anyone.
- Use the OS or a cryptographic source for adversarial shuffles.
- For tests, fixed seeds are fine. Just do not assume a seeded test covers all orderings.
Exercise
A tournament app shuffles 24 players into a bracket using a generator seeded with a 64-bit value. Can every bracket ordering occur? Use the tables above and explain.
Show answer
No. A 64-bit seed covers every ordering only up to 20 items, because 21! (about 5.1 × 10^19) already exceeds 2^64 (about 1.8 × 10^19). 24! is about 6.2 × 10^23, which needs at least 80 bits, so at most 2^64 of the 24! orderings can ever be produced, a fraction of roughly 3 × 10^-5. Seeding with 80 or more bits from the OS, or using the default OS-seeded generator, removes the cap.
Exercise
A colleague says, "We use Mersenne Twister with 19,937 bits of state, so our card shuffle can reach all 52! decks." Their code calls random.seed(user_id) with a 32-bit user ID before each shuffle. Is the claim correct?
Show answer
No. Each shuffle starts from a state set by the seed, and there are only 2^32 possible user IDs, so at most about 4.3 billion decks can occur, and the same user always gets the same deck. The state size is irrelevant when the seed space is smaller. The fix is to stop reseeding with the user ID and let the generator seed itself from the OS, or to use SystemRandom if the deck has value to players.
Exercise
Modify the toy LCG program so it reports how many of the 720 permutations are missing, and explain why a 16-bit state version, with 65,536 seeds, might still miss some permutations even though 65,536 is greater than 720.
Show answer
Print 720 - len(reachable). With 16 bits, reachability is possible but not guaranteed: different seeds can lead to the same permutation, and a low-quality generator with a biased index mapping may never produce certain index sequences. 2^k ≥ n! is a necessary condition, not a sufficient one. The generator's output must also be well distributed across the index choices.