http://en.wikipedia.org/wiki/IEEE_754-1985
The helpful Examples section already contains the numbers 0 and 1.
Let us assume that the output is supposed to be between 0 and 1; it seems that 0 should be inclusive and 1 exclusive for the most balanced 'quick' output.
Those two numbers have the leading binary format:
0 (8 or 11 bits exponent) (23 or 52 bits fraction) For either 32 or 64 bit floats.
Thus for a float (32 bit):
0 0 (7 bits) (23 bits) 30 bits of randomness are necessary, HOWEVER 0 01111111 is already one when the fraction is all 0s. The easiest solution I can see is to evenly drop some precision:
A reference for the casting procedure: http://en.wikipedia.org/wiki/Fast_inverse_square_root#Overvi...
Pseudo:
uint32 randomNumber;
... set the random somehow, maybe rand() maybe /dev/urandom etc ...
randomNumber &= 0x3F7FFFFF;
return * (float *) &randomNumber;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;
}Btw, what is the advantage of this over dividing? Is it faster, does it give better distribution?
It's probably a better design idea to have a predictable sequence of float (like, application dependent) results and randomly select from within said sequence.
Being more precise would probably require thinking about all the possible int values.