Sub topic 3
When the Random Generator Is Too Small
This chapter assumes you know the in-place Fisher-Yates loop from the previous chapter, basic Python, and what a uniform distribution is.
When the Random Generator Is Too Small
A pseudo-random number generator (PRNG) is deterministic. Its output depends only on its internal state. If the state holds b bits, the generator can produce at most 2^b different shuffles. A 52-card deck has 52! ≈ 2^226 orderings, so the state needs more than 226 bits.
| Generator state | Reachable orderings | Enough for 52 cards? |
|---|---|---|
| 32-bit seed | 2^32 | No |
| 64-bit state | 2^64 | No |
| Mersenne Twister (19937 bits) | 2^19937 | Yes |
Testing a Shuffle with Frequency Counts
Shuffle a small list many times and count how often each permutation appears. Then compute a chi-square statistic, which measures how far the counts are from even.
import random
from collections import Counter
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]
return items
trials = 60000
counts = Counter(tuple(fisher_yates([1, 2, 3])) for _ in range(trials))
expected = trials / 6
chi2 = sum((c - expected) ** 2 / expected for c in counts.values())
print(len(counts), round(chi2, 2)) # 6 permutations; chi2 should be below 11.07Six outcomes give 5 degrees of freedom. A statistic above 11.07 is suspicious at the 5% level. Also check that all six permutations appear at all.
Using Your Language's Built-In Shuffle
Python's random.shuffle already implements Fisher-Yates. Use random.SystemRandom().shuffle when the result must be unpredictable, for example for card games played for money or for security tokens.
Partial Shuffles: Picking k Random Items
Run the loop forward and stop after k steps. Each step swaps position i with a random index in [i, n-1], so the first k slots hold a uniform ordered sample. This costs O(k) swaps.
The Inside-Out Variant
The inside-out variant builds a shuffled copy while reading the input once. Item i goes to a random slot j in [0, i], and the item that was in slot j moves to the end. It works on streams and leaves the source unchanged.
Sattolo's Algorithm and Cyclic Permutations
Change randint(0, i) to randrange(i) and you get Sattolo's algorithm. Because j can no longer equal i, it produces only single-cycle permutations, each with probability 1/(n−1)!. That is correct when you want a random cycle and a bug when you want a general shuffle.
Exercise
Your shuffle of [1, 2, 3] produces only (2, 3, 1) and (3, 1, 2), each about half the time. What is wrong?
Show answer
The index range excludes i, so the code is running Sattolo's algorithm. Only the two 3-cycles can appear. Make the upper bound inclusive: j = random.randint(0, i).
Exercise
Can a PRNG with a 128-bit state reach every ordering of a 52-card deck?
Show answer
No. It reaches at most 2^128 orderings, and 52! is about 2^226.