I want to be able to generate random values between 0.0 and 1.0
I\'ve tried to use
std::default_random_engine generator;
std::uniform_real_distribu
If you are referring to the fact that you get the same results for each execution of the program, that's because you need to provide a seed based on some naturally random value (e.g. some number input by the user, or the number of milliseconds elapsed since the computer was turned on, or since January 1, 1970, etc.):
#include <random>
std::default_random_engine generator;
generator.seed( /* ... */ );
// ^^^^^^^^^
// Provide some naturally random value here
std::uniform_real_distribution<float> distribution(0.0, 1.0);
float myrand = distribution(generator);
// 1-st variant: using time() function for seed random distribution
std::default_random_engine generator(time(0));
std::uniform_real_distribution<double> distribution(first, last);
return distribution(generator);
If open multiple programs, with the same random number generator they will all output the same results, because they have the same value of seed which is time.
This issue solved by using random device, in the below code:
// 2-nd variant:
std::uniform_real_distribution<double> distribution(first, last);
std::random_device rd;
std::default_random_engine generator(rd());
return distribution(generator);
I have found another good solution...
double Generate(const double from, const double to)
{
std::random_device rd;
return std::bind(
std::uniform_real_distribution<>{from, to},
std::default_random_engine{ rd() })();
}