Boost random number generator

后端 未结 3 688
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 14:36

Does anyone have a favorite boost random number generator and can you explain a little on how to implement it into code. I am trying to get the mersenne twister to work and

3条回答
  •  春和景丽
    2020-11-27 15:08

    This code is adapted from the boost manual at http://www.boost.org/doc/libs/1_42_0/libs/random/index.html:

    #include 
    #include "boost/random.hpp"
    #include "boost/generator_iterator.hpp"
    using namespace std;
    
    int main() {
          typedef boost::mt19937 RNGType;
          RNGType rng;
          boost::uniform_int<> one_to_six( 1, 6 );
          boost::variate_generator< RNGType, boost::uniform_int<> >
                        dice(rng, one_to_six);
          for ( int i = 0; i < 6; i++ ) {
              int n  = dice();
              cout << n << endl;
         }
    }
    

    To explain the bits:

    • mt19937 is the mersenne twister generator,which generates the raw random numbers. A typedef is used here so you can easily change random number generator type.

    • rng is an instance of the twister generator.

    • one_to_six is an instance of a distribution. This specifies the numbers we want to generate and the distribution they follow. Here we want 1 to 6, distributed evenly.

    • dice is the thing that takes the raw numbers and the distribution, and creates for us the numbers we actually want.

    • dice() is a call to operator() for the dice object, which gets the next random number following the distribution, simulating a random six-sided dice throw.

    As it stands, this code produces the same sequence of dice throws each time. You can randomise the generator in its constructor:

     RNGType rng( time(0) );   
    

    or by using its seed() member.

提交回复
热议问题