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
Well considering simplicity and speed as your primary criteria, you can add a small generic helper like this :-
// C++ rand generates random numbers between 0 and RAND_MAX. This is quite a big range
// Normally one would want the generated random number within a range to be really
// useful. So the arguments have default values which can be overridden by the caller
int nextRandomNum(int low = 0, int high = 100) const {
int range = (high - low) + 1;
// this modulo operation does not generate a truly uniformly distributed random number
// in the span (since in most cases lower numbers are slightly more likely),
// but it is generally a good approximation for short spans. Use it if essential
//int res = ( std::rand() % high + low );
int res = low + static_cast( ( range * std::rand() / ( RAND_MAX + 1.0) ) );
return res;
}
Random number generation is a well studied, complex and advanced topic. You can find some simple but useful algorithms here apart from the ones mentioned in other answers:-
Eternally Confuzzled