問題描述
有人有最喜歡的 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.
這篇關于提升隨機數生成器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!