How do you generate a random double uniformly distributed between 0 and 1 from C++?
Of course I can think of some answers, but I\'d like to know what the standard pr
//Returns a random number in the range (0.0f, 1.0f).
// 0111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
// seee eeee eeee vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv
// sign = 's'
// exponent = 'e'
// value = 'v'
double DoubleRand() {
typedef unsigned long long uint64;
uint64 ret = 0;
for (int i = 0; i < 13; i++) {
ret |= ((uint64) (rand() % 16) << i * 4);
}
if (ret == 0) {
return rand() % 2 ? 1.0f : 0.0f;
}
uint64 retb = ret;
unsigned int exp = 0x3ff;
retb = ret | ((uint64) exp << 52);
double *tmp = (double*) &retb;
double retval = *tmp;
while (retval > 1.0f || retval < 0.0f) {
retval = *(tmp = (double*) &(retb = ret | ((uint64) (exp--) << 52)));
}
if (rand() % 2) {
retval -= 0.5f;
}
return retval;
}
This should do the trick, I used this Wikipedia article to help create this. I believe it to be as good as drand48();