From MDN (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random):
Math.random
Returns a floating-point, pseudo-random number in the range
[0, 1)
that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
But then, it says:
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for
Math.random()
itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 2^62) to calculate the usually-excluded upper bound.
Should I consider those cases? e.g., use...
Math.min(max, Math.floor(Math.random() * (max - min + 1)) + min);
...instead of...
Math.floor(Math.random() * (max - min + 1)) + min;
...?
How random is Math. random()? It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.
Math. random() returns a 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, using an implementation-dependent algorithm or strategy. This function takes no arguments.
The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).
The Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive).
If you called Math.random() a billion times a second, you should expect to encounter this error every 150 years or so. And I'm giving Javascript way too much credit for performance. :-)
No. Favor clarity and simplicity over "correctness" and bizarre edge-cases. This more complex code may trip up some poor developer (or maybe the future you) maintaining this code. The chance of that is greater than the 1 in 2^62 chance of Math.random() not working as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With