How to generate pseudo random numbers?


Pseudo random numbers are useful in several fields:


The "rand()" function is not suitable for scientific computations, since the quality is not enough.

The Mersenne Twister is reasonable.

Use "boost/random.hpp".


A sequence of pseudo random numbers on the [0,1] interval is generated as follows.

  #include <boost/random.hpp>  // header file
  #include <iostream> // for output

  double UniformRandom(int randomseed=1) //uniform random number generator
    static boost::mt19937 gen( static_cast<unsigned int>(randomseed) );
    static boost::uniform_real<> dst(0,1);
    static boost::variate_generator< boost::mt19937&, boost::uniform_real<> > rand(gen, dst);
    return rand();

  int main(void)
    for(int i=0; i<10; ++i)
       std::cout << UniformRandom(1) << std::endl;
    return 0;

You may change the "randomseed" (the argument of UniformRandom) arbitrarily to get different sequences of pseudo random numbers.

Last modified: Thu Aug 17 13:29:04 JST 2017