Is there a difference between the results of Math.floor(Math.random() * x) + 1
and Math.ceil(Math.random() * x)
?

- 37
- 5
-
If `Math.random() * x` is a integer they will have different values. However, the chance of that is small. – mousetail Jun 10 '22 at 13:48
-
Are you asking if there is any difference in the spread/likelihood of the random numbers this produces? – DBS Jun 10 '22 at 13:49
-
1The difference is the first can never return `0` and the second can. – Etheryte Jun 10 '22 at 13:49
-
2Math.random gives a number between 0 included and 1 excluded. Multiplying it by x gives a number between 0 included and x excluded. Therefore doing Math.floor + 1 or Math.ceil on that number gives the same result ( Random integer between 1 included and X included ) – Xavier B. Jun 10 '22 at 13:50
-
1Does this answer your question? [Better algorithm generating random numbers in JS](https://stackoverflow.com/questions/55172070/better-algorithm-generating-random-numbers-in-js) – FZs Jun 10 '22 at 13:56
-
1@XavierB. incorrect - `Math.floor(0 + 1) == 1`, but `Math.ceil(0) == 0` – Alnitak Jun 10 '22 at 14:19
2 Answers
Math.random()
produces floating point values in the interval [0, 1) (from zero inclusive to one exclusive). This means that there is a slight difference between the two approaches:
Math.ceil(Math.random() * x)
will produce integers in the interval [0, x] (from zero inclusive to x
inclusive). This is because Math.ceil(0)
will return a zero. Although the chance of getting that is extremely small.
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.ceil(minRandom() * x));
console.log("max:", Math.ceil(maxRandom() * x));
Math.floor(Math.random() * x) + 1
will produce integers in the interval [1, x] (from one inclusive to x
inclusive). This is because Math.floor(Math.random() * x)
itself produces integers in the interval [0, x-1] (zero inclusive to x-1
inclusive).
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.floor(minRandom() * x) + 1);
console.log("max:", Math.floor(maxRandom() * x) + 1);

- 26,331
- 9
- 49
- 67
Yes, there's a difference.
There is a chance, albeit a very very small one, that the second version could unexpectedly return zero.
This happens if Math.random()
itself returns exactly 0.0, which it legally can.

- 334,560
- 70
- 407
- 495
-
I'm not really sure it's unexpected. Well, unless you never wanted a zero. But it's a totally valid output. – VLAZ Jun 10 '22 at 13:58
-
1@VLAZ kinda - it's certainly valid, but it might surprise some people (including some of the other commentators here). – Alnitak Jun 10 '22 at 13:58
-
1¯\\_(ツ)_/¯ Any output can be a surprise if you don't know how something works. – VLAZ Jun 10 '22 at 14:02