我试图在Visual Studio C ++ 2010中进行高斯分布。每次运行时,我希望得到不同的结果。但是当我运行这段代码三遍时,结果是一样的:
#include <iostream>
#include <random>
int roundnew(double d)
{
return floor(d + 0.5);
}
int main()
{
std::default_random_engine generator;
std::normal_distribution<double> distribution(10,1);
for (int n = 0; n < 12; ++n) {
printf("%d\n",roundnew(distribution(generator)));
}
return 0;
}
结果是
10
9
11
9
10
11
10
9
10
10
12
10
我的代码有什么问题?它需要我的代码中的种子值,对吗?您可以在运行代码中看到结果
您需要为随机数生成器添加种子。
做这样的事情:
std::random_device rd;
std::default_random_engine generator;
generator.seed( rd() ); //Now this is seeded differently each time.
std::normal_distribution<double> distribution(10,1);
for (int n = 0; n < 12; ++n) {
{
printf("%d\n",roundnew(distribution(generator)));
}
std::random_device
应该生成不确定的数字,因此对您的播种目的应该是好的。每次运行程序都应为RNG创建一个不同的种子。请参阅:http : //en.cppreference.com/w/cpp/numeric/random/random_device(正如R. Martinho Fernandes指出的那样,在这方面缺少一些实现,因此,如果您正在做一些重要的事情,请检查实现细节。)
有关c ++随机数生成的更多详细信息,请参见:http : //www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3551.pdf
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句