Visit Mozilla.org

Talk:Core JavaScript 1.5 Reference:Global Objects:Math:random

From MDC

[edit] Potential rounding problems in snippet

I believe that the final code snippet (random integer between min and max) is incorrect due to potential floating point rounding error.

I am not 100% sure if this problem will strike in the real world, but sufficiently high less-than-one numbers can round upwards when multiplied. For example, in the Firefox JS engine:

>>> 0.9999999999999999 * 6
5.999999999999999
>>> 0.99999999999999999 * 6
6

I propose guarding against this case by replacing the following...

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

... with this...

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

This addition of a Math.min() call should only take effect in bugged cases, otherwise I believe it does no damage to the random distribution. Could somebody please comment on this issue before I make any changes to the page itself?

Dewi 22:44, 31 July 2007 (PDT)

While theoretically this is a concern, I don't think it will matter in practice. I added a note to the page mentioning the issue, which seems sufficient to me for the vast majority of uses. Also, I don't think your fix actually works, if we consider the random number as the greatest JS number strictly less than 1 and a wide variety of max/min values, where round-to-nearest-even will round up to the excluded value. --Waldo 11:44, 2 August 2007 (PDT)