Terminology (6)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Modulo bias
- Unequal chances from raw % k when the number of raw values is not a multiple of k.
- Rejection sampling
- Throwing away raw values at or above the last full multiple of k and drawing again.
- Fisher–Yates shuffle
- Walking from the last position down, swapping each with a uniformly chosen position at or before it. Every order is equally likely when the successive choices are independent and uniform.
- Seeded generator Also PRNG
- A generator whose sequence follows from its seed. The small noncryptographic generator here supports replay; cryptographic generators can also be seeded, with secret state.
- Cryptographic generator Also CSPRNG
- A generator whose outputs cannot be predicted from earlier ones. Required for tokens, keys and anything an attacker could exploit.
- xorshift32
- A small, fast 32-bit generator built from shifts and exclusive-or, used here so the web app, the mobile apps and the grading backend draw the same bytes.
Why this matters
Surveys assign versions, experiments assign users, load balancers pick backends and services generate tokens. Each step turns raw random bits into a choice. Small mapping mistakes make some choices more likely in a way no single run reveals, and a draw that has to be checked or replayed needs a generator and draw order everyone shares.
This lesson assumes modular arithmetic and expected values from earlier lessons.
Random draws and repeatable protocols
A uniform draw gives every allowed value the same probability. Turning raw generator values into a smaller set of choices is another operation: its fairness depends on how many raw values lead to each choice. Modular arithmetic lets you count those possibilities without relying on one random trial.
A seeded pseudorandom generator produces a deterministic sequence from its initial state. Reproducing an assignment or shuffle therefore requires agreement on the generator, the mapping and the order in which draws are consumed. Fairness arguments here assume independent uniform draws; a repeatable finite generator alone does not establish that assumption or provide the unpredictability needed for security tokens.
01Where modulo bias comes from
Where modulo bias comes from
A survey tool must assign questionnaire versions evenly and let the grading backend rebuild the answer order each respondent saw. Its byte % 6 assignment favors some versions, and the iPhone app’s shuffle disagrees with the backend even when they start from the same seed.
The tool’s version counts could be uneven by chance or because of the mapping. Enumerate every possible byte to separate those explanations. Assume each byte is equally likely, so N = 256 raw values and k = 6 versions. Predict the three lines this program prints.
// One random byte (0-255) turned into one of 6 survey versions with byte % 6.
const ways = Array<number>(6).fill(0);
for (let byte = 0; byte < 256; byte++) ways[byte % 6]!++;
const limit = 256 - (256 % 6); // redraw bytes at or above this
console.log(ways.join(" "));
console.log(limit);
console.log((256 / limit).toFixed(4));
The general rule: N = q × k + r. The first r outcomes get q + 1 raw values and the rest get q. With 32-bit values and a million outcomes the gap is 4,295 against 4,294, small but measurable over many draws.
02Reject and redraw
Reject and redraw
Keep only bytes below 252, the largest multiple of 6 that fits, and draw again otherwise. Each version now has exactly 42 bytes. A draw is kept with chance 252/256, so the expected number of draws per assignment is 256/252 ≈ 1.0159. The cost is worst when k is just above half of N: with 129 outcomes from a byte, almost half of all draws are thrown away.
Math.random cannot be seeded and is not cryptographic. Use crypto.getRandomValues for anything unpredictable, and a small seeded generator such as xorshift32 when a draw must be reproducible.
03Broken shuffles
Broken shuffles
Correct version counts do not guarantee fair answer orders. The tool also walks every answer option and swaps it with any position. With independent uniform choices, for 3 options that is 3 × 3 × 3 = 27 equally likely paths onto 6 orders, and 27 is not a multiple of 6: three orders come up 5 times in 27 and three 4 times. Fisher-Yates walks from the last position down and swaps it only with a position at or before it, giving 3 × 2 = 6 paths, one per order.
| Method | Paths | Per order |
|---|---|---|
| Swap each with any position | 27 | 4 or 5 |
| Fisher-Yates from the end | 6 | 1 |
04Draws are the contract
Draws are the contract
05Seeded or cryptographic
Seeded or cryptographic
06Shuffle the survey
Shuffle the survey
The survey team needs both balanced version assignment and a stable grading replay. Count the mapping’s imbalance, calculate the redraw limit and cost, then restore the agreed shuffle protocol. A loop using the right index range can still replay the wrong order if it consumes a byte that should have been rejected.
A survey’s randomizer
Find the modulo bias, assign versions fairly, then rebuild the answer order.
In the frontend A fair prize draw in Next.js and Svelte Optional
A prize draw among respondents uses crypto.getRandomValues for an unpredictable 32-bit value and redraws values at or above the last full multiple of the number of entries, so everyone has the same chance.
"use client";
import { useState } from "react";
// Every respondent in the prize draw equally likely: 32-bit values above the last full multiple are redrawn.
function pick<T>(entries: T[]): T {
const limit = 2 ** 32 - (2 ** 32 % entries.length);
const word = new Uint32Array(1);
do crypto.getRandomValues(word);
while (word[0]! >= limit);
return entries[word[0]! % entries.length]!;
}
export function DrawWinner({ respondents }: { respondents: string[] }) {
const [winner, setWinner] = useState<string | null>(null);
if (respondents.length === 0)
return <p>No respondents have entered the prize draw.</p>;
return (
<p>
<button onClick={() => setWinner(pick(respondents))}>Draw a winner</button>{" "}
{winner}
</p>
);
}
Check this idea later
Sources
- Marsaglia (2003), Xorshift RNGs
- Go: math/rand/v2
- C++: std::uniform_int_distribution
- Web Cryptography API: getRandomValues
Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The survey tool is a worked model.
Sign in to keep your read marks on every device. Sign in
Was this helpful?