mt19937和Uniform_real_distribution [英] mt19937 and uniform_real_distribution
问题描述
我正在尝试找到一种有效的方法来实现均匀的(0,1)分布.由于必须生成大量样本,因此我选择mt19937作为引擎.我正在使用boost库中的版本.我的问题是:使用引擎本身的输出与使用uniform_real_distribution之间有什么区别?
I am trying to find an efficient way to implement a uniform(0,1) distribution. Since I have to generate a very large number of samples, I chose mt19937 as engine. I am using the version from the boost library. My question is: what is the difference between using the output of the engine itself vs using uniform_real_distribution?
选项1
std::random_device rd;
boost::mt19937 gen(rd());
boost::random::uniform_real_distribution<double> urand(0, 1);
for ( int i = 0; i < 1E8; i++ ) {
u = urand(gen);
}
选项#2
std::random_device rd;
boost::mt19937 gen(rd());
for ( int i = 0; i < 1E8; i++ ) {
u = (double) gen()/gen.max();
}
根据我的测试,选项2在运行时方面明显优于选项1.有什么理由让我选择选项#1而不是选项#2?
From my tests, Option #2 is considerably better than Option #1 in terms of runtime. Is there any reason I should pick Option #1 over Option #2?
推荐答案
我不知道urand()
的基础实现,但是使用除法结果很可能会在低阶位产生偏差.量化效果.如果gen.max()
不大,则结果的低位"可能非常多或大部分.
I don't know the underlying implementation of urand()
, but using the result of a division is likely to produce bias in the low-order bits as a quantisation effect. If gen.max()
isn't large then "low-order bits" may be very many or most of the bits of the result.
性能差异可能来自产生适当分布的随机数.如果double
不能满足您的需求,那么使用float
可能会使它更有效地运行.
The performance disparity may come from producing properly distributed random numbers. If double
is overly precise for your needs then perhaps using float
might allow it to run more efficiently.
这篇关于mt19937和Uniform_real_distribution的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!