# Best way to generate a random double?

• 10-16-2001
The V.
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:

long l;
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.
• 10-16-2001
*pointer
Code:

```double rand_float( double low, double high ) {     return ( ( double )rand() * ( high - low ) ) / ( double )RAND_MAX + low; }```
• 10-16-2001
The V.
The problem with this, however, is that it is not uniformly distributed enough.

The reason is that there are only 32,768 different values of rand(). So, there will only be 32,768 different doubles that this can return -- it can return 0/32767, 1/32767, 2/32767, ... 32767/32767

The problem with this is that it is not uniform enough. It has equal probability of returning any multiple of 1/32767, but it has zero probability of returning anything *between* these values.

I'm looking for a way to generate a random double that is random over about 15 to 20 decimal places -- so there must be something in the range of 10^15 to 10^20 possible values that it can take on.
• 10-16-2001
Salem
If you want better generators (better than the standard library function), then wander over to here....