我正在做一些随机数生成并获得可疑行为.这是我的代码:
// 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.
}
Run Code Online (Sandbox Code Playgroud)
我是否误用了boost中的随机抽样?我做错了什么使它总是相同的价值.我在构造函数中初始化随机数生成器,因此它应该总是吐出不同的值(不重新初始化)
问题在于线路boost::variate_generator< boost::mt19937, boost::normal_distribution<> > resampler(*rng, distribution);.此构造函数按值获取其参数(请参阅文档).因此,每个都resampler使用相同的生成器副本开始并调用一次.
编辑:沙菲克在我做了之后就注意到了同样的事情.如果你真的无法将初始化提升到循环之外,你也可以重新为种子生成种子.根据您的应用,有很多方法可以实现此目的.以下只是一个例子:
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.
}
Run Code Online (Sandbox Code Playgroud)
注意:不要rng仅使用重新播种time(NULL),因为如果您test()在紧密循环中调用,可能会多次返回相同的值.