Reputation: 5339
I am trying to generate a random number that range from Number.MIN_VALUE to Number.MAX_VALUE, but the following algorithm fails due to buffer overflows (I guess) :
var randFloat = Math.floor(Math.random() * (Number.MAX_VALUE - Number.MIN_VALUE)) + Number.MIN_VALUE
Is there any way to do it ?
Upvotes: 1
Views: 366
Reputation: 254926
What you could do:
function IEEEToDouble(f)
{
return new Float64Array(f.buffer)[0];
}
var array = new Uint32Array(2); // here we allocate a 2 element unsigned 32 bit ints
window.crypto.getRandomValues(array); // here we generate 64 bits of random values
var f = IEEEToDouble(array); // and convert 64 bits to a double precision number
This generates a uniformly distributed double precision IEEE754 number. So every possible value in the whole space is equally possible to get with this code, including NaN
s (it's quite a lot of NaN
s there actually - 2^53 - 2
) and Infinity
s.
References:
IEEEToDouble
function borrowed from https://stackoverflow.com/a/21282715/251311Upvotes: 1