News for hackers. Stuff that matters.
Re:Libsodium 1.0.0 released by gjm11 on Wednesday September 24, 2014 @08:45PM (#8364962)
If you put 0 (i.e., plus) in the sign bit, and 1023 (i.e., zero) in the exponent field, and 52 random bits in the fraction field, of an IEEE double, then you get a number between 1 (inclusive) and 2 (exclusive); the representable numbers in that range are evenly spaced, and if your random bits are good then they are all equally likely, so you've got a uniform random number between 1 and 2. Subtract 1 if you want a uniform random number between 0 and 1 (this doesn't lose information; if a number between 1 and 2 is representable, subtracting 1 yields a representable number).

If your machine happens to work the same way as mine, the following will do it (unportable, untested, yadda yadda):

    double randomDouble() {
      uint64_t bits = random64bits();
      bits &= ~(3ull<<62); // clear sign and MSB of expt
      bits |= (1023ull<<52); // rest of exponent is 1-bits
      return (*(double*)&bits) - 1;
    }
Re:Libsodium 1.0.0 released by ZoFreX on Wednesday September 24, 2014 @09:41PM (#8365117)
Interesting, I'll test this. Thanks!

Btw, what is the advantage of this over dividing? Is it faster, does it give better distribution?

Re:Libsodium 1.0.0 released by lmm on Thursday September 25, 2014 @03:12AM (#8366008)
It should be faster than dividing. It will give you a uniform distribution over some (but not all) of the representable values between 0.0 and 1.0 (there are as many representable values between e.g. 0.25 and 0.5 as there are between 0.5 and 1.0, so a uniform distribution over representable values probably isn't what you want), which is probably as good as you can do.