Sub topic 11
Testing a Shuffle with Frequency Counts
This chapter assumes you can read Python, know what a permutation is and why there are n! of them, and have seen both the Fisher-Yates shuffle and the biased naive shuffle from earlier chapters. You also need basic probability: expected value and the idea that a fair process can still produce uneven counts by chance.
A proof tells you the algorithm is correct. It does not tell you that your code is correct. One wrong loop bound or a bad random-index helper can make the code biased while it still looks fine. An empirical test runs the shuffle many times, counts the outcomes, and checks whether the counts are consistent with a uniform distribution. The test can never prove a shuffle is fair. It can show that a shuffle is unfair, often within seconds.
The Testing Workflow
Counting Full Permutations
For small n you can count every permutation directly. With n = 3 there are 6 orderings. A fair shuffle run 60,000 times should give each one about 10,000 hits. The question is how far from 10,000 a count can drift before you stop blaming chance.
The chi-square statistic answers that. For each category, take the observed count O and the expected count E, and add up (O − E)² / E. A fair shuffle gives a small sum. A biased one gives a sum that grows with the number of trials.
import random
from collections import Counter
from itertools import permutations
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
def naive_shuffle(items):
n = len(items)
for i in range(n):
j = random.randint(0, n - 1) # the bug: any index
items[i], items[j] = items[j], items[i]
return items
def frequency_table(shuffle, n=3, trials=60000):
return Counter(tuple(shuffle(list(range(1, n + 1)))) for _ in range(trials))
def chi_square(counts, categories, trials):
expected = trials / len(categories)
return sum((counts.get(c, 0) - expected) ** 2 / expected for c in categories)
random.seed(2026) # fixed seed so the test is reproducible
n, trials = 3, 60000
all_perms = list(permutations(range(1, n + 1)))
for name, shuffle in [("fisher_yates", fisher_yates), ("naive", naive_shuffle)]:
counts = frequency_table(shuffle, n, trials)
stat = chi_square(counts, all_perms, trials)
print(name)
for perm in all_perms:
print(" ", perm, counts.get(perm, 0))
print(" chi-square =", round(stat, 1))A typical run looks like this:
| Permutation | Fisher-Yates | Naive |
|---|---|---|
| (1, 2, 3) | ≈ 10,000 | ≈ 8,900 |
| (1, 3, 2) | ≈ 10,000 | ≈ 11,100 |
| (2, 1, 3) | ≈ 10,000 | ≈ 11,100 |
| (2, 3, 1) | ≈ 10,000 | ≈ 11,100 |
| (3, 1, 2) | ≈ 10,000 | ≈ 8,900 |
| (3, 2, 1) | ≈ 10,000 | ≈ 8,900 |
| Chi-square | usually under 11 | about 740 |
The naive numbers match the counting argument. Of the 27 equally likely swap sequences, three permutations get 5 each and three get 4 each. So the probabilities are 5/27 and 4/27 instead of 1/6 = 4.5/27.
Reading the Statistic
To judge the statistic, compare it with a critical value from the chi-square distribution. That distribution has degrees of freedom equal to the number of categories minus one, because the counts must add up to the number of trials. For n = 3 there are 6 − 1 = 5 degrees of freedom.
| Degrees of freedom | Critical value, α = 0.05 | Critical value, α = 0.001 |
|---|---|---|
| 5 | 11.07 | 20.52 |
| 9 | 16.92 | 27.88 |
| 23 | 35.17 | 49.73 |
α is the false-alarm rate. At α = 0.05 a perfectly fair shuffle will exceed the critical value in about 1 run out of 20. That rate is fine for one exploration. It is too high for a test suite that runs on every commit. If you have SciPy installed, it computes the statistic and a p-value for you:
from scipy.stats import chisquare
observed = [10051, 9968, 9940, 10012, 10077, 9952] # counts for the 6 permutations
result = chisquare(observed) # expected defaults to equal counts
print(result.statistic, result.pvalue)A small p-value (say below 0.001) means counts this uneven would rarely come from a uniform shuffle. A large p-value means the data do not show bias. It does not mean the shuffle is proven fair.
How Many Trials You Need
Two rules set the sample size.
- Minimum cell size. The chi-square approximation needs expected counts of at least about 5 per category. More is better, and in practice you want hundreds.
- Power. For a fixed bias, the statistic grows roughly in proportion to the number of trials. If the true probabilities are p and the uniform ones are q, the expected statistic is about trials × Σ (p − q)² / q, plus the degrees of freedom. A large bias like the naive shuffle's shows up within a few thousand trials. A bias of 0.1% in one cell might need tens of millions.
Plan the trial count from the smallest bias you care about, not from whatever finishes quickly.
Scaling Up: Position Counts
Full permutation counting stops working quickly. For n = 10 there are 3,628,800 permutations, so you would need hundreds of millions of trials to fill every cell. Instead, count where each item lands. In a fair shuffle, item i ends up at each of the n positions with probability 1/n. That gives an n × n table.
import random
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
def naive_shuffle(items):
n = len(items)
for i in range(n):
j = random.randint(0, n - 1)
items[i], items[j] = items[j], items[i]
return items
def position_counts(shuffle, n, trials):
counts = [[0] * n for _ in range(n)] # counts[item][position]
for _ in range(trials):
result = shuffle(list(range(n)))
for pos, item in enumerate(result):
counts[item][pos] += 1
return counts
def row_chi_square(row, trials):
expected = trials / len(row)
return sum((o - expected) ** 2 / expected for o in row)
random.seed(7)
n, trials = 10, 100000
critical = 27.88 / 1 # df = 9, alpha = 0.001 per row
for name, shuffle in [("fisher_yates", fisher_yates), ("naive", naive_shuffle)]:
counts = position_counts(shuffle, n, trials)
stats = [row_chi_square(row, trials) for row in counts]
flagged = [item for item, s in enumerate(stats) if s > critical]
print(name, "max row chi-square:", round(max(stats), 1), "flagged items:", flagged)Test each row on its own. One item's final position is a single draw from n positions, so each row is a clean multinomial with n − 1 degrees of freedom. The cells of the whole table depend on each other, because every trial adds exactly one to each row and to each column. That makes a single chi-square over all n² cells only approximate.
Running 10 row tests at α = 0.001 gives about a 1% chance that a fair shuffle trips at least one. This is the multiple testing problem. If you need a tighter overall rate, divide α by the number of tests (the Bonferroni correction).
Pitfalls in Shuffle Tests
- Reusing the input list. In-place shuffles change their argument. If you shuffle the same list repeatedly, each trial starts from the last result. Fisher-Yates stays uniform in that case, but some biased shuffles look fairer than they are. Pass a fresh
list(range(n))every trial. - Flaky tests. An unseeded statistical test fails at random about α of the time. In CI, fix the seed and use a strict α such as 0.001. Run an unseeded, larger version occasionally to check the code path that uses real randomness.
- Testing the wrong generator. A seeded test exercises
random.randint. If production usessecretsorrandom.SystemRandom, test that code path too. Bias in a custom index helper, such as modulo bias, only shows up when you test the helper you actually ship. - Sizes too small to show the bug. Modulo bias from a 32-bit source with a small range is far too small for any practical trial count to detect. Frequency tests catch logic errors like wrong bounds or naive swaps. For subtle range bias, read the code or test the helper with an artificially small source range.
- Treating a pass as proof. "No bias detected" depends on your sample size. Report the trial count along with the result.
Exercise
You test a shuffle on [1, 2, 3, 4] with 24,000 trials and get a chi-square statistic of 41.3 across the 24 permutations. Using α = 0.001, what do you conclude? What would you check first in the code?
Show answer
There are 24 − 1 = 23 degrees of freedom, and the critical value at α = 0.001 is about 49.73. Since 41.3 is below it, the test does not detect bias at that level. It would exceed the α = 0.05 value of 35.17, though, so rerun with several times more trials before trusting the result. If the statistic keeps rising in proportion to the trial count, the shuffle is biased. Check the loop bounds and the range passed to the random-integer call first.
Exercise
A colleague's test computes sum((count - expected) ** 2 / expected for count in counter.values()) for an n = 3 shuffle, and it passes. Their shuffle uses random.randrange(i) instead of random.randint(0, i). Why did the test pass, and what does the shuffle actually produce?
Show answer
random.randrange(i) excludes i, so the code is Sattolo's algorithm. For n = 3 it produces only the two 3-cycles, (2, 3, 1) and (3, 1, 2), each about half the time. The test loops over counter.values(), so the four permutations that never appear are left out. It then compares two cells against an expected value of trials/6. A correct loop over all 6 permutations, with zero counts filled in, gives a huge statistic (about 2 × trials).
Exercise
Why is a per-row chi-square on the position table valid with n − 1 degrees of freedom, while a single test over all n² cells is only approximate?
Show answer
Each row records where one item lands in each trial. That is one independent draw from n positions per trial, so the row is multinomial and loses one degree of freedom for its fixed total. Across the whole table, every trial adds exactly one count to every row and to every column. Those extra constraints link the cells, so the plain multinomial chi-square formula no longer applies exactly.