C ++ normal_distribution和MATLAB的randn的实现是否一致?

时间:2014-02-03 18:21:29

标签: c++ matlab c++11 statistics normal-distribution

我正在使用Mersenne twister,以便在Matlab和C ++中的项目之间获得一致的随机值。但是在使用randn或C ++ 11 normal_distribution时,我无法获得一致的正态分布伪随机值。

这是C ++:

void main()
{
    unsigned int mersenneSeed = 1977;
    std::mt19937_64 generator; // it doesn't matter if I use the 64 or the std::mt19937
    generator.seed(mersenneSeed);
    std::normal_distribution<double> normal; // default is 0 mean and 1.0 std
    double temp = normal(generator); 
        // results 1.4404780513814264 for mt19937_64 and 1.8252033038258377 for mt19937
}

这是Matlab:

rng(1977) % default Matlab uses mersenne twister
randn()   % default is 0 mean and 1.0 std

我正在使用Matlab 2013b和Visual Studio Express 2013.我是否在使用C ++ 11正态分发做错了什么?

1 个答案:

答案 0 :(得分:1)

Mersenne twister本身只生成32位整数随机数。您观察到的差异最可能的解释是这些均匀分布的整数如何转换为正态分布的双精度浮点数。

由于randn的文档没有解释这种转换,并且源代码不可用(它是一个内置函数),如果没有逆向工程,很难再说明这一点。 (根据Casey的评论,对于C ++方面来说似乎也是如此。)

实现一致性的最简单方法可能是在C ++ Matlab中生成随机数,保存结果,并根据需要加载它们。另一种方法是在C ++中将自己的Matlab随机数函数编写为MEX file(使用C ++的normal_distribution),并在Matlab中使用此函数而不是randn