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.
Asked
Active
Viewed 3,677 times
3 Answers
8
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
.

Konrad Rudolph
- 530,221
- 131
- 937
- 1,214
-
@stonybrooknick Unfortunately, [Boost doesn’t seem to have it](http://www.boost.org/doc/libs/1_46_1/doc/html/boost_random/reference.html#boost_random.reference.distributions) but it shouldn’t be too hard to implement once you look at how the other distributions are implemented and how the PDF is defined. – Konrad Rudolph Dec 07 '11 at 07:26
-
@stonybrooknick: By "beta" you either mean a scale parameter or a rate parameter. In the first case multiply the variates by beta, otherwise divide them. – Neil G Jan 08 '12 at 15:34
6
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).

Howard Hinnant
- 206,506
- 52
- 449
- 577
1
Looks like Gamma Distribution in Boost has some code that will do what you want. The bit you're probably missing is boost::variate_generator
.

Community
- 1
- 1

Gareth McCaughan
- 19,888
- 1
- 41
- 62