Bojan Nikolic: Numerical and Quantitative Methods in C++

[website home] | [BN Algorithms]

Uniform integer random numbers on a user-defined rangeΒΆ

The uniform integer generators previously mentioned produce numbers distributed over the full range of the integer type that is passed to them. Quite often however, a random number from a smaller, user defined range is required. This is very easily implemented using the boost::uniform_int<> class. For example this is the code to produce random numbers between 1 and 6 inclusive:

#include <iostream>

#include <boost/random/uniform_int.hpp>
#include <boost/random/mersenne_twister.hpp>

int main(void)
{
  boost::mt19937 eng;
  boost::uniform_int<size_t> gen(1,6);

  for (size_t i=0; i < 50; ++i)
  {
    std::cout<<gen(eng)
	     <<std::endl;
  }

  
}

There are only a couple of things worth noting with regard to this code:

  • The class boost::uniform_int<> is initialised with the minimum and maximum numbers that define the range. Both of the numbers supplied are included in the range.
  • At the time that the random number is required, an engine which produces uniform random numbers over the full domain of the type must be supplied – this is usually called the “engine” for this distribution. In this case I’ve used the Mersenne twister generator.