views:

190

answers:

2

I need to generate quickly lots of random numbers from binomial distributions for dramatically different trial sizes (most, however, will be small). I was hoping not to have to code an algorithm by hand (see, e.g., this related discussion from November), because I'm a novice programmer and don't like reinventing wheels. It appears Boost does not supply a generator for binomially distributed variates, but TR1 and GSL do. Is there a good reason to choose one over the other, or is it better that I write something customized to my situation? I don't know if this makes sense, but I'll alternate between generating numbers from uniform distributions and binomial distributions throughout the program, and I'd like for them to share the same seed and to minimize overhead. I'd love some advice or examples for what I should be considering.

+4  A: 

Boost 1.43 appears to support binomial distributions. You can use boost::variate_generator to connect your source of randomness to the type of distribution you want to sample from.

So your code might look something like this (Disclaimer: not tested!):

boost::mt19937 rng;                 // produces randomness out of thin air
                                    // see pseudo-random number generators
const int n = 20;
const double p = 0.5;
boost::binomial<> my_binomial(n,p);      // binomial distribution with n=20, p=0.5
                                         // see random number distributions
boost::variate_generator<boost::mt19937&, boost::binomial<> >
         next_value(rng, my_binomial);     // glues randomness with mapping
int x = next_value();                      // simulate flipping a fair coin 20 times
Jim Lewis
If I understand it correctly, it does not actually support PRNGs from those distributions. It calculates probability and cumulative mass functions and the like.
Sarah
Gah, now I get it. Thank you--your example is helpful.
Sarah
+2  A: 

You misunderstand the Boost model - you choose a random number generator type and then a distribution on which to spread the values the RNG produces over. There's a very simple example in this answer, which uses a uniform distribution, but other distributions use the same basic pattern - the generator and the distribution are completely decoupled.

anon
Heh, I'm so not quick enough for Boost. Thanks for explaining what it's doing.
Sarah