开发者

Random numbers from binomial distribution

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 be开发者_开发百科tween 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜