std::default_random_engine generate values between 0.0 and 1.0

34,676

Solution 1

// 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);

Solution 2

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);

Solution 3

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() })();
}
Share:
34,676
user1185305
Author by

user1185305

Updated on January 24, 2020

Comments

  • user1185305
    user1185305 over 4 years

    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_distribution<float> distribution(0.0, 1.0);
    
    float myrand = distribution(generator);
    

    Generating random value in a loop gives me always these values:

    0.000022
    
    0.085032
    
    0.601353
    
    0.891611
    
    0.967956
    
    0.189690
    
    0.514976
    
    0.398008
    
    0.262906
    
    0.743512
    
    0.089548
    

    What can I do to really get random values? Doesn't seem that random if I always get the same ones.

  • us2012
    us2012 about 11 years
    +1 for random_device - if you know it's available on the systems your program should run, I like this solution best.
  • miracle173
    miracle173 about 6 years
    std::random_device rd was already proposed two years ago here
  • Caleth
    Caleth over 4 years
    Initialising a new std::random_device and std::default_random_engine each time seems excessive