Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c++ - Boost random number generator

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 was wondering if anyone had preference towards one of the others.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

#include <iostream>
#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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...