Magix
Magix

Reputation: 5339

Can I generate a random float on the whole space?

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

Answers (1)

zerkms
zerkms

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 NaNs (it's quite a lot of NaNs there actually - 2^53 - 2) and Infinitys.

References:

Upvotes: 1

Related Questions