Should I consider the possibility of 1 in 2 ^ 62 getting the excluded upper bound when using `Math.random ()`?

From MDN ( https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random ):

Math.random

Returns a pseudo-random floating-point number in the range [0, 1) that is, from 0 (inclusive) to, but not including 1 (excluding), which can then be scaled to the desired range.

But then he says:

Please note that as numbers in JavaScript are IEEE 754 floating-point numbers rounded to the nearest and even behavior, these ranges, with the exception of one for Math.random() , are not exact and depend on boundaries, this is possible in extremely rare cases ( order 1 in 2 ^ 62) to calculate the usually excluded upper bound.

Should I consider these cases? for example, use ...

 Math.min(max, Math.floor(Math.random() * (max - min + 1)) + min); 

... instead of ...

 Math.floor(Math.random() * (max - min + 1)) + min; 

...

+8
javascript random
source share
2 answers

If you called Math.random () a billion times per second, you should encounter this error every 150 years or so. And I give Javascript too many credits for performance. :-)

+6
source share

Not. Contribute to clarity and simplicity over "correctness" and fancy edge cabinets. This more complex code may disable some bad developer (or, possibly, the future) supporting this code. The likelihood of this is greater than the likelihood that Math.random () will be less than expected.

+2
source share

All Articles