Take the 2-minute tour ×

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.

share|improve this question
add comment

2 Answers

up vote 47 down vote accepted

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);
          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.

share|improve this answer
Hey thanks a lot that explains a lot –  shinjuo Feb 12 '10 at 23:24
Nice post, and very detailed explanation! –  Matthieu M. Mar 23 '10 at 13:28
And is there any way of the min and max of the integer distribution be changed without having to construct a new "dice"? –  J. C. Leitão Jun 5 '12 at 12:58
add comment

There's no one-size-fits-all RNG. Sometimes statistical properties are important, sometimes cryptology, sometimes raw speed.

share|improve this answer
I wasnt necessarily wanting a one size fits all, I just know that some people prefer one over the other and I wanted to see which ones people liked best. –  shinjuo Feb 14 '10 at 3:19
add comment

Your Answer


