Reputation: 13
I am making a simple exercise in JavaScript in which I have to generate a random number between 1 and 3 in JavaScript and found this:
return Math.floor(Math.random() * (max - min + 1) + min);
But with a friend we figured out that we can use Math.round instead for the same purpose:
return Math.round(Math.random() * (max - min) + min);
What caught our attention is that the last formula is not being suggested anywhere on Internet (as far as we were able to search for it...).
Are there any explanation about why this is not used?
We have tried to confirm why return Math.round(Math.random() * (max - min) + min);
is not being suggested for the use of generating random numbers instead/or as an alternative to return Math.round(Math.random() * (max - min) + min);
Upvotes: 0
Views: 469
Reputation: 2534
We can run a simple experiment to see why using Math.round
will not give the results you want. We'll run each function 100,000 times and count how many of each result we get.
When using Math.floor
, you can see that the distribution of all the items is approximately equal (~20,000 here)
let min = 0;
let max = 5;
let counts = [];
for (let i = 0; i < 100_000; i++) {
const index = Math.floor(Math.random() * (max - min) + min);
if (!counts[index]) counts[index] = 0;
counts[index]++;
}
console.log(counts);
But with Math.round
, the first and last values will have around half the values of the others. This is because part of the values that should be going to them are being rounded into the other values.
let min = 0;
let max = 5;
let counts = [];
for (let i = 0; i < 100_000; i++) {
const index = Math.round(Math.random() * (max - min) + min);
if (!counts[index]) counts[index] = 0;
counts[index]++;
}
console.log(counts);
Upvotes: 3