How can I get a uniformly distributed random number from the interval [0, 1]?
I am currently using the following code, but it is in C and I would like to know how one does things in C++ instead.
double RND()
{
    return ((double)rand()/RAND_MAX);
}
How can I get a uniformly distributed random number from the interval [0, 1]?
I am currently using the following code, but it is in C and I would like to know how one does things in C++ instead.
double RND()
{
    return ((double)rand()/RAND_MAX);
}
 
    
     
    
    This is actually somewhat tricky to do correctly. For integers, the uniform distribution class produces numbers in the range [min...max], but for real numbers, the range is [min ... max). To get [0 .. 1.0], we need to add a small number to the upper end of the range. As it happens, since our number is 1.0, the standard library gives us exactly the correct number to add as the epsilon() for the target type:
std::mt19937_64 gen{ std::random_device()() };
std::uniform_real_distribution<double> dis{
    0.0,
    1.0 + std::numeric_limits<double>::epsilon()
};
epsilon is the smallest number that can be added to 1.0 and produce a result that compares greater than 1.0, so this allows numbers up to (and including) 1.0, but no greater--precisely the requested range.
 
    
    You could use the <random> library added in C++11. See cplusplus.com for more information on distribution and different RNGs.
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
double number = distribution(generator);
EDIT: As pointed out by Captain Giraffe, above code will be for the range [0,1) and not [0,1]. Use T.C.'s suggested std::uniform_real_distribution<double> distribution(0.0,std::nextafter(1.0, 2.0)); to get a closed upper bound.
