Simple normally distributed random number generation

Here is a very simple program that illustrates how to generate normally distributed random numbers using boost.

#include <time.h>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>

int main(void)
{
  boost::variate_generator<boost::mt19937, boost::normal_distribution<> >
    generator(boost::mt19937(time(0)),
              boost::normal_distribution<>());

  double r = generator();
}

I think the above is precise and relatively compact. If you need to use this same object often in your code, then of course you should make use of typedefs to avoid having to type template parameters every time.

If you are wondering why can't it be simpler and maybe allow you to use:

#inlcude <boost/random.hpp>
double r = Random(MarsenneTwister, NormalDistribution);

The answer is that:

  • Namespaces are an important and useful part of the language. Without namespaces C++ would become more cumbersome. In your .cc/.cpp files you are free to make using namespace statements if you wish.
  • The short form would be opaque and inflexible with respect to how the underlying random number generator is seeded and advances. Is the seed set from process time? Or from "/dev/random"? Does each call advance the seed? Or each call within a thread? Or each call within a function?
  • You can't change the basic parameters of the normal distribution (mean and variance).