Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gamma distributed random variables in C++

What is the easiest way to get a gamma distributed random variable in C++? Boost seems to have this functionality, but it is not clear for me how to use it.

like image 944
Grzenio Avatar asked Mar 31 '11 12:03

Grzenio


2 Answers

It’s pretty straightforward:

boost::mt19937 rng;
boost::gamma_distribution<> pdf(alpha);
boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> >
    generator(rng, pdf);

Constructs a random number generator and a gamma distribution and glues them together into a usable generator. Now you can create random numbers by invoking the generator.

like image 123
Konrad Rudolph Avatar answered Oct 12 '22 00:10

Konrad Rudolph


Here is how you do it in C++11:

#include <random>
#include <iostream>

int main()
{
    typedef std::mt19937 G;
    typedef std::gamma_distribution<> D;
    G g;  // seed if you want with integral argument
    double k = .5;      // http://en.wikipedia.org/wiki/Gamma_distribution
    double theta = 2.0;
    D d(k, theta);
    std::cout << d(g) << '\n';
}

Your compiler may or may not yet support <random>. Boost random has just recently been modified to conform to the std::syntax, but I'm not sure if that modification has actually been released yet (or is still just on the boost trunk).

like image 33
Howard Hinnant Avatar answered Oct 12 '22 01:10

Howard Hinnant