Generating Random Numbers in C++ with Boost.Random

The boost libraries (boost.org) are high regarded C++ libraries, and a lot of those libraries have ended up being accepted in the C++ standard.

TheBoost.Random library is a great library for generating random numbers. If offers a wide range of random number generators, and a wide range of distribution to sample from.

The code snippet below generates 10 standard normal distributed random numbers using the Boost.Random library.

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
 
int main()
 { 
    typedef boost::mt19937                     ENG;    // Mersenne Twister
    typedef boost::normal_distribution<double> DIST;   // Normal Distribution
    typedef boost::variate_generator<ENG,DIST> GEN;    // Variate generator
 
    ENG  eng;
    DIST dist(0,1);
    GEN  gen(eng,dist);
 
    for (int i = 0; i < 10; i++)
        std::cout << gen() << std::endl;
 
    return 0;
}

Output

0.213436
-0.49558
1.57538
-1.0592
1.83927
1.88577
0.604675
-0.365983
-0.578264
-0.634376