std::default_random_engine generate values between 0.0 and 1.0

后端 未结 3 2018
北恋
北恋 2020-12-17 15:39

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         


        
相关标签:
3条回答
  • 2020-12-17 16:04

    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);
    
    0 讨论(0)
  • 2020-12-17 16:15
    // 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);
    
    0 讨论(0)
  • 2020-12-17 16:19

    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() })();
    }
    
    0 讨论(0)
提交回复
热议问题