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.
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 tooperator()
for thedice
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.
There's no one-size-fits-all RNG. Sometimes statistical properties are important, sometimes cryptology, sometimes raw speed.