Rolling a d100 in JavaScript: Modulo Bias, Math.random, and Rejection Sampling
Mapping 2^32 values onto a d100 biases some faces by about 2e-10. The bias is calculable but no χ² test can see it; the roller removes it for correctness.
Every consumer dice roller on the first page of Google rolls a die the same way: Math.floor(Math.random() * sides) + 1. ECMA-262 §21.1.2.13 is explicit that Math.random returns "an implementation-approximated Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range" — pseudo randomly is in the normative text. V8, SpiderMonkey, and JavaScriptCore all ship xorshift128+. None of them claim to be a CSPRNG, and none of them have to be. Seeing a few dozen outputs is enough to recover the 128-bit state and predict every later value.
The second issue is the mapping. For any sides that is not a power of two, a uniform draw over 2^k values cannot split evenly into sides outcomes, even if the generator itself were perfect. Take a 32-bit draw and x % 100: 2^32 mod 100 = 96, so faces 1-96 each get 42,949,673 of the 2^32 values and faces 97-100 get 42,949,672. Each of the four short faces comes up with probability 1/100 − 2.24e-10; the other 96 get 1/100 + 9.3e-12. Math.floor(Math.random() * sides) has the same structure over the 52 or 53 random bits of a double, so its bias is smaller still, around 1e-16.
The bias is real and can be computed exactly, but no statistical test will find it. For a d100 with 32-bit modulo mapping, a Pearson χ² test gains a noncentrality of about 2.1e-17 per roll. A 50% chance of rejecting uniformity at α = 0.05 takes about 1.2 × 10^18 rolls. At a few thousand rolls the test cannot tell this die from a perfect one: p-values fall below 0.05 about 1 run in 20 either way.
This roller uses W3C Web Crypto crypto.getRandomValues plus Daniel Lemire's 2019 rejection-sampling algorithm. The reason is correctness, not an observable difference: rejection sampling makes the mapping exactly uniform, and getRandomValues is a CSPRNG. A Statistics panel runs a live Pearson χ² test against a uniform distribution on every roll; it catches implementation bugs such as a missing face, not a 2e-10 bias.
Lemire 2019 in Five Lines
Daniel Lemire, "Fast Random Integer Generation in an Interval," ACM TOMS 2019. The classical "draw a uniform integer in [1, N]" recipe is: draw a 32-bit integer x, compute limit = floor(2^32 / N) * N, accept if x < limit, otherwise redraw. The rejection rate is exactly (2^32 mod N) / 2^32. For N = 100, that is 96 / 2^32 ≈ 2.235e-8. For N = 6, it is exactly 4 / 2^32 ≈ 9.31e-10. The expected number of draws is 1 / (1 − reject), which is 1.000000022 for d100.
const ROLL_BUF = new Uint32Array(1);
export function rollDie(sides: number): number {
const limit = Math.floor(0x1_0000_0000 / sides) * sides;
for (let iter = 0; iter < 1024; iter++) {
crypto.getRandomValues(ROLL_BUF);
const x = ROLL_BUF[0];
if (x < limit) return (x % sides) + 1;
}
throw new Error("Rejection sampling failed to terminate");
}
The ROLL_BUF is a module-level Uint32Array(1) singleton. A 6d6 sum allocates zero arrays past first call; getRandomValues writes into the existing buffer. The 1024-iteration cap exists only to surface caller misuse (e.g. someone passing sides = 2^32), since the geometric expectation for any reasonable sides is 1 + 2.3e-8. On a hot path the loop almost never enters its second iteration.
The rollDie function is called exclusively from React event handlers — never from a render body or a useMemo. Re-renders aggregate into the histogram from state; they never re-roll.
The Live χ² Histogram
A Pearson goodness-of-fit χ² against a uniform expected distribution is:
χ² = Σ (observed_i − expected)² / expected
with expected = total / sides and df = sides − 1. The p-value comes from the upper regularized incomplete gamma: p = Q(df/2, χ²/2). The implementation evaluates Q via Numerical Recipes' branch-cut — gamma series for x < s+1, continued fraction otherwise, with a Lanczos g=7 log-gamma. Results are memoized by ${df}|${chi2.toFixed(4)} in a 256-entry LRU, so switching between dice in the Statistics panel does not re-compute the special function for a χ² value it has already seen.
What the panel shows: roll a d20 thirty times and the p-value is meaningless (the histogram is too sparse). With a few hundred rolls from a uniform RNG, the p-value is itself uniformly distributed between 0 and 1, so about 1 run in 20 lands below 0.05 by chance.
Turning off "Secure randomness" switches rolls to Math.floor(Math.random() * sides) + 1. The panel will not tell the two generators apart: xorshift128+ passes simple frequency tests, and the mapping bias is many orders of magnitude below what a χ² test can resolve at this scale. The reasons to avoid Math.random for dice are that it is not a CSPRNG and its mapping is not exactly uniform, not that a test will catch it.
D&D Stat Array: Brute Enumerate, Don't Sample
The D&D 5e stat-array preset rolls 4d6kh3 six times. The theoretical mean of 4d6kh3 is not 14 (a common rule-of-thumb) and not 12.5. The exact value is:
E[4d6kh3] = 15869 / 1296 ≈ 12.2446
with Var = 8.105 and SD ≈ 2.847. This comes from enumerating all 6^4 = 1296 outcomes, sorting each, dropping the lowest, and summing the top three. The expected sum of one rolled stat is 15869 / 1296; for six independent stats the total is 6 × 15869 / 1296 ≈ 73.47. The probability of rolling an 18 on any single stat is 21 / 1296 ≈ 1.62% (the one (6,6,6,6) outcome plus the twenty (6,6,6,x) outcomes for x ∈ {1..5} across four positions).
These numbers are constants in STAT_ARRAY_THEORY, frozen at module load. The roller displays them alongside the empirical mean of your last N rolls so you can see convergence at a glance. After a hundred stat arrays you should be within ~0.15 of 12.2446; after a thousand, within ~0.05. If not, the histogram is the next place to look.
Why Exploding Dice Need a Hard Cap
Savage Worlds "Aces" rolls 1d6!: roll a d6, and on a 6 roll again and add. The expected value is the geometric series 3.5 + (1/6) × 3.5 + (1/6)^2 × 3.5 + ... = 3.5 / (1 − 1/6) = 4.2 exactly. The variance is finite because the geometric tail decays fast.
The implementation still caps explosion chains at 50 per die. On a clean d6 the probability of a chain longer than 50 is (1/6)^50 ≈ 1.23e-39, which never happens on Earth. The cap exists because a malformed input (1d2!, where every other face is the max face) would otherwise hand a tight loop to the renderer. Same for the r reroll modifier: capped at 50 consecutive rerolls of the same face. The parser also refuses Nd1! outright with infiniteExplode, because every face equals the max and the chain never terminates.
The chain cap is a defensive boundary, not a math one. With well-formed TTRPG dice (d4/d6/d8/d10/d12/d20/d100), the cap is unreachable by ten orders of magnitude.
Try It
Open the Dice Roller.
- Math.random comparison: in the Quick roll tab, turn off
Secure randomness, set the count to 100, and pressd100fifty times (5,000 rolls). Select d100 in the Statistics panel. The p-value behaves the same as with the toggle on: below 0.05 in about 1 run in 20. Showing the bias would take on the order of10^18rolls. - Stat Array preset: click
4d6 keep highest 3 × 6. After about 100 sets your running mean per stat should be within 0.15 of 12.2446. The displayedE = 15869/1296is the brute-force enumeration of all 1296 outcomes. - Exploding d6: type
1d6!into the notation tab, roll 1,000 times. Empirical mean should hover within 0.05 of 4.2 — exactly3.5 / (1 − 1/6). - Shadowrun success count: type
6d6>=5, roll. Thekeptfield shows the integer success count (faces ≥ 5), not the sum. Probability per die is2/6 = 1/3, so the expected count is 2.
The toggle exists so you can compare the two generators yourself.