Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I consider the 1 in 2^62 possibility of 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 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;

...?

like image 362
Oriol Avatar asked May 26 '13 00:05

Oriol


People also ask

Is math random () really random?

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.

How does math random generate a random number?

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.

What values does math random return?

The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

Which of the following value is known as exclusive returned by math random ()?

The Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive).


2 Answers

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. :-)

like image 137
Lee Daniel Crocker Avatar answered Oct 05 '22 02:10

Lee Daniel Crocker


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.

like image 23
Mike Grassotti Avatar answered Oct 05 '22 02:10

Mike Grassotti