有人有最喜欢的 boost 随机数生成器吗?你能解释一下如何将它实现到代码中吗?我试图让梅森龙卷风工作,并想知道是否有人偏爱其他人.
Does anyone have a favorite boost random number generator and can you explain a little on how to implement it into code. I am trying to get the mersenne twister to work and was wondering if anyone had preference towards one of the others.
此代码改编自 http://www.boost.org/doc/libs/1_42_0/libs/random/index.html:
#include <iostream>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
using namespace std;
int main() {
typedef boost::mt19937 RNGType;
RNGType rng;
boost::uniform_int<> one_to_six( 1, 6 );
boost::variate_generator< RNGType, boost::uniform_int<> >
dice(rng, one_to_six);
for ( int i = 0; i < 6; i++ ) {
int n = dice();
cout << n << endl;
}
}
解释一下:
mt19937
是梅森扭曲器生成器,它生成原始随机数.此处使用了 typedef,因此您可以轻松更改随机数生成器类型.
mt19937
is the mersenne twister generator,which generates the raw random numbers. A typedef is used here so you can easily change random number generator type.
rng
是twister 生成器的一个实例.
rng
is an instance of the twister generator.
one_to_six
是分布的一个实例.这指定了我们要生成的数字及其遵循的分布.这里我们想要 1 到 6 个,均匀分布.
one_to_six
is an instance of a distribution. This specifies the numbers we want to generate and the distribution they follow. Here we want 1 to 6, distributed evenly.
dice
是获取原始数字和分布的东西,并为我们创建我们真正想要的数字.
dice
is the thing that takes the raw numbers and the distribution, and creates for us the numbers we actually want.
dice()
是对 dice
对象的 operator()
调用,该对象获取紧随其后的下一个随机数分布,模拟随机六面掷骰子.
dice()
is a call to operator()
for the dice
object, which gets the next random number following the distribution, simulating a random six-sided dice throw.
就目前而言,这段代码每次都会产生相同的掷骰子序列.您可以在其构造函数中随机化生成器:
As it stands, this code produces the same sequence of dice throws each time. You can randomise the generator in its constructor:
RNGType rng( time(0) );
或使用其 seed() 成员.
or by using its seed() member.
这篇关于提升随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!