Skip to content
Advertisement

Write a truly inclusive random method for javascript

Javascript’s MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

e.g.

var rand = MATH.random()*2;

if(rand > 1)
{
   rand = MATH.floor(rand);
}

return rand; 

While this always returns a number from the set [0,1] it is not truly random.

Advertisement

Answer

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 wi’ll 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.

8 People found this is helpful
Advertisement