Sub topic 14
Random Integers in a Range and the Limits of Math.random
This chapter assumes you know how Math.floor and Math.round behave from the previous chapter, and that you can run JavaScript in Node.js (version 19 or later) or a browser console. It covers how to turn Math.random() into integers you can trust for games, sampling, and UI work. It also explains when you should not use Math.random() at all.
What Math.random Actually Returns
Math.random() takes no arguments. It returns a Number x where 0 <= x < 1. The interval is half-open: it can return 0, but it never returns 1. The specification asks for an approximately uniform distribution, which means every part of the interval is about equally likely. The specification does not name the algorithm. V8, the engine behind Chrome and Node.js, currently uses xorshift128+. Other engines may use something else.
The specification also leaves out some things:
- You cannot seed it. Two runs of the same program give different sequences, and you cannot replay a sequence for testing.
- It is not cryptographically secure. Someone who observes enough outputs can predict the ones that follow.
- Its resolution is limited. The results are doubles in [0, 1), so there are at most 2^53 distinct values, and some engines produce fewer.
From [0, 1) to an Inclusive Integer Range
To get an integer from min to max inclusive, you stretch the interval, shift it, and cut off the fraction.
function randomInt(min, max) {
// Returns an integer from min to max, inclusive
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // e.g. 4Each step does one job:
max - min + 1is the number of possible results. For a die, that is6 - 1 + 1 = 6.- Multiplying gives a float in
[0, 6). Math.floorproduces 0, 1, 2, 3, 4, or 5. Each integer owns a slice of the interval of width 1.- Adding
minshifts the results to 1 through 6.
Because Math.random() never returns 1, the product never reaches 6, and max can never overflow by one.
Common Errors and Why They Fail
Using Math.round Instead of Math.floor
This version looks reasonable, but it is biased:
function biasedInt(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}When min is 1 and max is 6, the float lies in [0, 5). Math.round sends [0, 0.5) to 0 but sends [0.5, 1.5) to 1. The two end values each get a slice half as wide as the inner values. You can measure this:
function tally(fn, trials = 600000) {
const counts = {};
for (let i = 0; i < trials; i++) {
const n = fn(1, 6);
counts[n] = (counts[n] || 0) + 1;
}
return counts;
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function biasedInt(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}
console.log(tally(randomInt)); // each face near 100000
console.log(tally(biasedInt)); // 1 and 6 near 60000, faces 2 to 5 near 120000Other Frequent Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Omitting `+ 1` in the range | `max` is never produced | Use `max - min + 1` |
| `Math.ceil` instead of `Math.floor` | `min` is produced only when `Math.random()` returns exactly 0, which almost never happens | Use `Math.floor` |
| `parseInt(Math.random() * n)` | Very small floats stringify as `"5e-7"`, so `parseInt` reads `5` | Use `Math.floor` or `Math.trunc` |
| Non-integer bounds such as `1.5` | Results are non-integers | Validate with `Number.isInteger`, or apply `Math.ceil(min)` and `Math.floor(max)` |
| `min > max` | Results fall outside the range you meant | Swap the bounds or throw |
Here is a hardened version:
function randomIntChecked(min, max) {
if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max)) {
throw new TypeError("min and max must be safe integers");
}
if (min > max) [min, max] = [max, min];
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomIntChecked(10, 1)); // an integer from 1 to 10For very wide ranges, where max - min is close to 2^53, the formula still runs. However, Math.random() does not have enough distinct values to reach every integer evenly, so wide ranges are a weak spot even before security comes up.
Picking and Shuffling
To pick a random element, use the same formula with min at 0:
const colors = ["red", "green", "blue"];
const pick = colors[Math.floor(Math.random() * colors.length)];
console.log(pick);To shuffle an array, a common shortcut is arr.sort(() => Math.random() - 0.5). Do not use it. The comparator breaks the consistency rules that sort relies on, so the results depend on the sort algorithm and come out measurably biased. Use the Fisher–Yates shuffle instead:
function shuffle(array) {
const a = array.slice();
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // 0..i inclusive
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
console.log(shuffle([1, 2, 3, 4, 5]));The index j must be drawn from 0..i inclusive. If you draw it from 0..a.length-1 on every step, the result is a different shuffle that is also biased.
When Math.random Is the Wrong Tool
crypto.getRandomValues fills a typed array with unpredictable values from the operating system's secure generator:
const bytes = new Uint32Array(1);
crypto.getRandomValues(bytes);
console.log(bytes[0]); // integer from 0 to 4294967295
console.log(crypto.randomUUID()); // e.g. "3b241101-e2bb-4255-8caf-4136c566a962"Modulo Bias and Rejection Sampling
A secure source alone is not enough. bytes[0] % 6 is still biased, because 2^32 is not a multiple of 6, so the smallest remainders come up slightly more often. The fix is rejection sampling: throw away raw values in the final incomplete block and draw again.
function secureRandomInt(min, max) {
if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min > max) {
throw new RangeError("invalid bounds");
}
const range = max - min + 1;
if (range > 2 ** 32) throw new RangeError("range too large for 32-bit source");
const limit = Math.floor(2 ** 32 / range) * range; // largest multiple of range
const buf = new Uint32Array(1);
let x;
do {
crypto.getRandomValues(buf);
x = buf[0];
} while (x >= limit);
return min + (x % range);
}
console.log(secureRandomInt(1, 6)); // unbiased and unpredictableIn Node.js, require("node:crypto").randomInt(min, maxExclusive) does the same job. Note that its upper bound is exclusive.
Choosing a Generator
| Need | Use |
|---|---|
| Visual effects, games, casual sampling | `Math.random()` with `Math.floor` |
| Tokens, IDs, secrets, fair draws | `crypto.getRandomValues` with rejection sampling, or `crypto.randomUUID()` |
| Reproducible sequences for tests or simulations | A seeded PRNG library (for example, a small mulberry32 or xoshiro implementation) |
Exercise
A coworker writes Math.round(Math.random() * 10) to get an integer from 0 to 10. What is the probability of getting 0, compared with getting 5, and how should the line be rewritten?
Show answer
Results of 0 come only from [0, 0.5), a width of 0.5. Results of 5 come from [4.5, 5.5), a width of 1. So 0 (and 10) each have probability 0.05, while 5 has 0.1, half as likely at the ends. Rewrite it as Math.floor(Math.random() * 11), which gives each of the 11 values a probability of 1/11.
Exercise
In secureRandomInt(1, 6), what is limit, and roughly how often does the loop have to draw again?
Show answer
The range is 6. Math.floor(4294967296 / 6) is 715827882, so limit is 715827882 * 6 = 4294967292. Only the 4 values from 4294967292 to 4294967295 are rejected, so a redraw happens with probability 4 / 2^32, about 1 in a billion.
Exercise
Why is [1, 2, 3].sort(() => Math.random() - 0.5) not a fair shuffle, and what should replace it?
Show answer
The comparator gives inconsistent answers for the same pair, which breaks the contract sort depends on. The resulting order depends on the engine's sort algorithm, and some orders come out more often than others. Use a Fisher–Yates shuffle that draws j from 0..i inclusive at each step.