[c++] How do you generate a random double uniformly distributed between 0 and 1 from C++?

double randDouble()
{
  double out;
  out = (double)rand()/(RAND_MAX + 1); //each iteration produces a number in [0, 1)
  out = (rand() + out)/RAND_MAX;
  out = (rand() + out)/RAND_MAX;
  out = (rand() + out)/RAND_MAX;
  out = (rand() + out)/RAND_MAX;
  out = (rand() + out)/RAND_MAX;

  return out;
}

Not quite as fast as double X=((double)rand()/(double)RAND_MAX);, but with better distribution. That algorithm gives only RAND_MAX evenly spaced choice of return values; this one gives RANDMAX^6, so its distribution is limited only by the precision of double.

If you want a long double just add a few iterations. If you want a number in [0, 1] rather than [0, 1) just make line 4 read out = (double)rand()/(RAND_MAX);.