Write a truly inclusive random method for javascript

The Math.random function returns a random number between 0 and 1, where 0 is inclusive and 1 is exclusive. This means that the only way to properly distribute the random numbers as integers in an interval is to use an exclusive upper limit.

To specify an inclusive upper limit, you just add one to it to make it exclusive in the calculation. This will distribute the random numbers correctly between 7 and 12, inclusive:

var min = 7;
var max = 12;
var rnd = min + Math.floor(Math.random() * (max - min + 1));

To put it bluntly, what you're trying to do doesn't make sense.

Remember that under a continuous probability distribution, the probability of getting a specific value is infinitesimal, so mathematically speaking you will never see the exact value of 1.

Of course, in the world of computers, the distribution of an RNG isn't truly continuous, so it's "possible" that you'll encounter a specific value (as silly as that sounds), but the probability will be so vanishingly small that in practice you will never observe it.

To make the point a bit more clearly: if you did manage to write such a function in terms of double-precision floats, the probability of getting exactly 1 would be approximately 2-64. If you called the function 1 million times per second, you would have to wait around 600,000 years before you got a 1.


You want it to include 1?

return 1 - Math.random();

However, I think this is one of those questions which hints at other problems. Why do you need to include 1? There's probably a better way to do it.


This will return [0,1] inclusive:

if(MATH.random() == 0)
    return 1;
else
    return MATH.random();

Explanation: If the first call to random() returns 0, return 1. Otherwise, call random again, which will be [0,1). Therefore, it will return [0,1] all inclusive.