Best way to generate a random double?
What's the best way to get a random double between 0 and 1?
I thought of rand() /RAND_MAX, but the problem with this is, it only returns rational numbers of the form x/32767. And 1/32767 is not all that small -- this "step size" is only on the order of 10^-5 -- so it's not really a good way to get a random double that should be random to more than this many decimal places. In other words, the smallest increment between random numbers generated by this method is on the order of 10^-5.
Currently, I have a function which uses a character array that is 20 characters long -- it randomly fills each with '0' through '9', it prepends "0." and uses the atof() to return the double corresponding to the string. This should give me a random number that is of the form x * 10^-20, so the smallest increment between random numbers is on the order of 10 ^ -20. This obviously gives a more uniform distribution over 0 and 1, and this is probably more than adequate for anything I'd need.
But, is there a better way to generate a random double than generate 20 random ints? I have to believe there's a more efficient way of getting a random double between 0 and 1 which is uniformly distributed to this degree.
My other idea was using rand to generate a random signed long like so:
l = rand() | ((long)rand() << 15) | (((long)rand() & 0x0001) << 30);
and then divide this by 0x7FFFFFFFL to get a random double.
(The shifting by 15 and 30, BTW, is because rand will return a value which is random in the first 15 bits).
The smallest increment here between random values is on the order of 10^-10, though, so the distribution isn't as uniform as the 20-char method.