c++ - 为什么 boost 的随机数生成(正态分布)总是给出相同的值?

标签 c++ boost random

我正在生成一些随机数并出现可疑行为。这是我的代码:

    // 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.
    }

我是否滥用了 boost 中的随机采样?我做错了什么使它始终具有相同的值(value)。我在构造函数中初始化了随机数生成器,因此它应该始终吐出不同的值(不会重新初始化)

最佳答案

问题出在 boost::variate_generator< boost::mt19937, boost::normal_distribution<> > resampler(*rng, distribution); 行.此构造函数按值获取其参数(请参阅 the documentation )。所以每个 resampler从生成器的相同拷贝开始并调用它一次。


编辑:Shafik 在我之后注意到了同样的事情。如果你真的不能将初始化 boost 到循环之外,你也可以重新设置生成器的种子。根据您的应用程序,有多种方法可以完成此操作。下面只是一个例子:

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只有 time(NULL) ,因为如果您调用 test() 可能会多次返回相同的值在一个紧密的循环中。

关于c++ - 为什么 boost 的随机数生成(正态分布)总是给出相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747194/

相关文章:

python - 将随机样本列添加到数据框中

c++ - 并行调用 std::vector 中的函数

php - 随机图像背景更改 PHP CSS

c++ - 两个整数之间的随机函数生成器 C++

c++ - boost::filesystem::exists 崩溃

C++ 语法 : return statement with space after "template"; what does it mean

c++ - 我迷失在 boost 库中(特别是 boost_program_options)

c++ - while 循环中不保留变量值

java - Eclipse插件,调用C++ dll

C++ : lvalue required as unary ‘&’ operand