std :: mt19937不返回随机数 [英] std::mt19937 doesn't return random number
问题描述
我有以下代码:
unsigned int randomInt()
{
mt19937 mt_rand(time(0));
return mt_rand();
};
如果我在for循环中调用此代码(例如4000次),则不会得到随机的无符号整数,而不会得到例如1000次一个值,而接下来的1000次将获得下一个值.
If I call this code, for example 4000 times in a for loop, I don't get random unsigned integers, instead I get for example 1000 times one value and the next 1000 times I get the next value.
我在做什么错了?
推荐答案
之所以会发生这种情况,是因为您在一个循环中调用f
4000次,这可能不到一毫秒,因此每次调用time(0)
都会返回相同的结果值,因此使用相同的种子初始化伪随机数生成器.正确的方法是一劳永逸地初始化种子,最好通过std::random_device
进行初始化,就像这样:
This happens because you call f
4000 times in a loop, which probably takes less than a mili second, so at each call time(0)
returns the same value, hence initializes the pseudo-random generator with the same seed. The correct way is to initialize the seed once and for all, preferably via a std::random_device
, like so:
#include <random>
#include <iostream>
static std::random_device rd; // random device engine, usually based on /dev/random on UNIX-like systems
// initialize Mersennes' twister using rd to generate the seed
static std::mt19937 rng(rd());
int dice()
{
static std::uniform_int_distribution<int> uid(1,6); // random dice
return uid(rng); // use rng as a generator
}
int main()
{
for(int i = 0; i < 10; ++i)
std::cout << dice() << " ";
}
这篇关于std :: mt19937不返回随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!