Generating Random Numbers in C++

Generating random numbers in C++ has long relied on the venerable rand() function. However times have changed (and they did so a while ago) and there is now a new random number facility that replaces rand(), this is the library Boost.Random. Boost.Random is not just another boost library, it was taken as the basis for the new random number facilities in the C++ Technical Report 1 (TR1) proposal in 2005 and will be part of the upcoming C++0x. So it really is the future and if your still using rand() to serve your random number generating needs then you should get on board and get up to date!

This tutorial gives a quick demonstration of how to use Boost.Random in the simplest case with a fully working code sample. There is a great deal more that you can do with Boost.Random but chances are this is all you will need.

Generating Random Numbers in a Range

The following sample generates a single random number in the range 1 to 10.


#include "boost/random.hpp"

#include <iostream>
#include <ctime>

int main(int c, char** argv)
{
  const int rangeMin = 1;
  const int rangeMax = 10;
  typedef boost::uniform_int<> NumberDistribution;
  typedef boost::mt19937 RandomNumberGenerator;
  typedef boost::variate_generator<RandomNumberGenerator&,
                                   NumberDistribution> Generator;

  NumberDistribution distribution(rangeMin, rangeMax);
  RandomNumberGenerator generator;
  Generator numberGenerator(generator, distribution);
  generator.seed(std::time(0)); // seed with the current time

  std::cout << numberGenerator() << std::endl;

} // main

Generating Floating Point Random Numbers

Due to the design of Boost.Random this is trivial to accomplish and all you need to do is make a four character change to the above example to achieve it. To do this just change the distribution type from int to real.


typedef boost::uniform_real<> NumberDistribution;

Leave a Comment