Search code examples
javarandomunderflow

Generate random double from random long


in Java I have a random generator that generates random number from -2^63 to 2^63 and that is NOT the java.util.Random.

I need to generate random double in (0,1), this is what I've done so far:

return (seed/(double)(9223372036854775807L))/2+0.5;//seed is a random long

Is this right? Are there any numerical problem (underflow?)?

Could be better/faster?

Thank you.


Solution

  • I would use Math.scalb as the most efficient and ensures there is no funny behaviour due to rounding or representation error

    double d = Math.scalb(seed >>> 1, -63);
    

    You can only use 53 bits in a double so some will be discarded.

    If you run

    long seed = Long.MAX_VALUE;
    System.out.println(Math.scalb(seed >>> 1, -63));
    

    prints

    0.5
    

    With a seed of 0 you get 0.0

    With a seed of -1 you get 1.0