A really quick boost::random guide

— richardwb on Wednesday, May 06, 2009 @ 20:03

This is a really short and quick guide on how to use boost::random. The best place to start is, as always, the documentation, but Boost also provides a simple sample program that covers the library in a good "how to get started" fashion.

What I'm about to write here is even shorter and less detailed -- it's just the basic code needed to generate some random numbers.

// Initialize a random number generator.
// Boost provides a bunch of these, note that some of them are not meant
// for direct user usage and you should instead use a specialization (for 
// example, don't use linear_congruential and use minstd_rand or 
// minstd_rand0 instead)

// This constructor seeds the generator with the current time.
// As mentioned in Boost's sample program, time(0) is not a great seed,
// but you can probably get away with it for most situations.
// Consider using more precise timers such as gettimeofday on *nix or
// GetTickCount/timeGetTime/QueryPerformanceCounter on Windows.
boost::mt19937 randGen(std::time(0));

// Now we set up a distribution. Boost provides a bunch of these as well.
// This is the preferred way to generate numbers in a certain range.
// In this example we initialize a uniform distribution between 0 and the max
// value that an unsigned char can hold (255 for most architectures)
boost::uniform_int<> uInt8Dist(0, std::numeric_limits<unsigned char>::max());

// Finally, declare a variate_generator which maps the random number
// generator and the distribution together. This variate_generator
// is usable like a function call.
boost::variate_generator< boost::mt19937&, boost::uniform_int<> > 
    GetRand(randGen, uInt8Dist);

// Generate a random number
int aRandomNumber = GetRand();
comments powered by Disqus