Search code examples
c++c++11random

Where is it better to store random_device/mt19937?


I have a function which makes use of randomness

void fun() {
    random_device rd;
    mt19937 gen(rd());
    uniform_real_distribution<double> dis(0.0, 1.0);
    // ...
}

And, as I suspect, I'll get poor random if it's call repeatedly and both rd and gen are created each time. Is it better to make these variables global/private fields of a class so they are not redeclared multiple times?


Solution

  • A random number generator should be a global object. But there is nothing wrong with burying it in a function for access:

    template <typename RealType>
    RealType random_real_in_range( RealType min = 0., RealType max = 1. )
    {
      thread_local std::mt19937 rng( std::random_device{}() );
      return std::uniform_real_distribution<RealType>( min, max )( rng );
    }
    

    The drawback here is that MT really should be “warmed up” by calling .discard( 1000 ) or so...