1

我正在尝试从正态分布中生成随机数。当代码:

normal(eng)

出现在 main() 中,程序运行正常。但是,如果它是从另一个函数调用的,则来自 main 的下一次调用将返回先前生成的相同值。下面是一些说明这一点的代码。输出的前几行是:

-0.710449
-0.710449
0.311983
0.311983
1.72192
1.72192
0.303135
0.303135
0.456779
0.456779

有谁知道为什么会这样?

编译器是 Windows 上的 gcc 4.4.1。

#include <iostream>
#include <cmath>
#include <ctime>
#include <tr1/random>

typedef std::tr1::ranlux64_base_01 Engine;
//typedef std::tr1::mt19937 Engine;
typedef std::tr1::normal_distribution<double> Normal;

double random_normal(Engine eng, Normal dist) {
    return dist(eng);
}

int main ( int argc, char** argv ) {
    Engine eng;
    eng.seed((unsigned int) time(NULL));

    Normal normal(0,1);

    for (int i = 0; i < 100; i++)
    {
        std::cout << random_normal(eng, normal) << std::endl;
        std::cout << normal(eng) << std::endl;   
    }

    return 0;
}
4

1 回答 1

3

发生这种情况是因为您将引擎按值传递给 random_normal。random_normal 获取引擎的副本,因此原始引擎没有修改其状态,直接使用原始引擎将产生与 random_normal 获得的相同结果。

如果您修改 random_normal 以通过引用获取引擎:

double random_normal(Engine &eng, Normal Dist);

那么原始引擎将被修改,您将不会得到重复的值。所有的标准发行版都通过引用它们的引擎。例如:

template<class IntType = int>
class uniform_int_distribution
{
...
    // generating functions
    template<class URNG>
    result_type operator()(URNG& g);
于 2012-05-11T18:07:05.497 回答