Boost Code Snippets

Generate a random number using boost

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>

boost::variate_generator<boost::mt19937, boost::uniform_real<float> >
     rnd(boost::mt19937(), boost::uniform_real<float>(0.0f, 1.0f) );
rnd() return a uniform random number between 0 and 1

Initialize the random number generator and use different generators in the same file

// initialize the unique generator using std::time(0)
boost::mt19937 mt ( static_cast<unsigned int>( std::time(0)) );

boost::variate_generator<boost::mt19937 &, boost::uniform_real<double> >
frand(mt, boost::uniform_real<double>(0.0, 1.0) );

boost::variate_generator<boost::mt19937 &, boost::uniform_real<double> >
brand(mt, boost::uniform_real<double>(-1.0, 1.0) );
  boost::variate_generator<boost::mt19937, boost::normal_distribution<> >
    generator(boost::mt19937(time(0)),
           boost::normal_distribution<>());

[ Back to home ]