为什么升压的随机数生成(对正态分布)始终给予同样的价值? [英] Why is boost's random number generation (on a normal distribution) always giving the same values?

查看:143
本文介绍了为什么升压的随机数生成(对正态分布)始终给予同样的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些随机数生成和获取腥的行为。这里是我的code:

I am doing some random number generation and getting fishy behaviour. Here is my code:

    // initialized earlier... in the constructor of a class
    boost::mt19937 *rng = new boost::mt19937();
    rng->seed(time(NULL));

    // actual use here.
    for (int i = 0; i < 10; ++i)
    {
        test();
    }


    void test()
    {
       boost::normal_distribution<> distribution(10, 10);
       boost::variate_generator< boost::mt19937, boost::normal_distribution<> > resampler(*rng, distribution);

       const double sample = (resampler)(); // always the same value.
    }

我是不是在滥用提振随机抽样?我做了什么不对的始终是相同的值。我初始化在构造函数中随机数生成器,所以应该经常吐出一个不同的值(没有得到重新初始化)

Am I misusing the random sampling in boost? What have I done wrong to make that always be the same value. I initialize the random number generator in the constructor so it should always spit out a different value (not getting reinitialized)

推荐答案

问题是与行的boost :: variate_generator&LT;提高:: mt19937,提振:: normal_distribution&LT;&GT; &GT;重采样器(RNG *,分布); 。此构造按值取它的参数(请参见文档)。因此,每个重采样开始与发电机的相同副本,一旦调用它。

The problem is with the line boost::variate_generator< boost::mt19937, boost::normal_distribution<> > resampler(*rng, distribution);. This constructor take its parameters by value (see the documentation). So each resampler starts off with an identical copy of the generator and calls it once.

编辑:沙菲克注意到了同样的事情只是一个小我做了。如果你真的不能挂起初始化圈外,还可以重新播种发电机。有很多方法可以做到这一点取决于你的应用程序。下面就是一个例子:

Shafik noticed the same thing just a little after I did. If you really can't hoist the initialization out of the loop, you can also re-seed the generator. There are many ways to accomplish this depending on your application. Below is just one example:

void test()
{
   static unsigned int seed = 0
   rng->seed((++seed) + time(NULL));

   boost::normal_distribution<> distribution(10, 10);
   boost::variate_generator< boost::mt19937, boost::normal_distribution<> > resampler(*rng, distribution);

   const double sample = (resampler)(); // always the same value.
}

注:不重新播种 RNG 只有时间(NULL),因为这可以返还相同价值几倍,如果你叫在一个紧密的循环测试()

Note: do not re-seed rng with just time(NULL), as that may return the same value several times if you call test() in a tight loop.

这篇关于为什么升压的随机数生成(对正态分布)始终给予同样的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆