二项分布的随机数

Sar*_*rah 4 c++ random tr1 gsl

我需要从二项式分布中快速生成大量随机数,以获得截然不同的试验大小(但大多数都会很小).我希望不必手动编写算法(例如,参见11月的相关讨论),因为我是一名新手程序员并且不喜欢重新发明轮子.看来Boost不为二元分布的变量提供发电机,但TR1GSL可以.是否有充分的理由选择其中一个,或者我更好地根据自己的情况编写一些东西?我不知道这是否有意义,但我将在整个程序中从均匀分布和二项分布生成数字之间交替,我希望它们共享相同的种子并最小化开销.对于我应该考虑的内容,我会喜欢一些建议或例子.

Jim*_*wis 6

Boost 1.43似乎支持二项分布.您可以使用boost::variate_generator将随机源连接到要从中进行采样的分布类型.

所以你的代码可能看起来像这样(免责声明:未经测试!):

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
Run Code Online (Sandbox Code Playgroud)