Home - TIL - Zines

Getting Even Distribution with JavaScript Random Numbers

When rounding numbers you should use Math.floor() in combination with Math.random() to get an even distribution of random numbers. You should not use Math.round() or Math.ceil().

Math.floor()

Let’s start with the correct example.

let picks = [0, 0, 0, 0, 0, 0];
let min = 1;
let max = 6;
// Loop 1k times
for (i=1;i<=1000000;i++) {
    // Pick one random number
    picked = Math.floor(Math.random() * max) + min;
    // Subtract one from the pick for an index on the zero based array
    picks[picked-1]++;
}
console.log(picks);

Math.round()

So, floor works great, but why can’t we just use Math.round()? Well, because it’s rounded in both directions the bottom number will never be rounded down and the top number will never be rounded up. That means that the bottom and top numbers are about half as likely as the remaining numbers.

Here’s a bit of code you can run to demonstrate the problem.

let picks = [0, 0, 0, 0, 0, 0];
let min = 1;
let max = 6;
// Loop 1k times
for (i=1;i<=1000000;i++) {
    // Pick one random number
    picked = Math.round(Math.random() * (max - 1)) + min;
    // Subtract one from the pick for an index on the zero based array
    picks[picked-1]++;
}
console.log(picks);

Math.ceil()

You might think that Math.ceil() would work too, but Math.random() picks a number between 0 inclusive and 1 exclusive. Meaning that it may pick a 0 but it will never pick a 1.

Here’s a bit of code you can run to demonstrate the problem. This will take a long time to run and you still might not see the problem. This is because the chance of a zero is very, very low.

let picks = [0, 0, 0, 0, 0, 0];
let max = 6;
// Loop a bunch of times
for (i=1;i<=1000000;i++) {
    // Pick one random number
    picked = Math.ceil(Math.random() * max);
    // Subtract one from the pick for an index on the zero based array
    picks[picked-1]++;
}
console.log(picks);


Do you have a question? I want to hear from you!

Ask Me Anything

JoelDare.com © Dare Companies Dotcom LLC

Terms - Privacy