[英]Why is <random> library producing the same results every time when using std::uniform_int_distribution
Notes: 笔记:
Here is the code: 这是代码:
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
srand(time(0));
long long seed = rand();
std::default_random_engine rand_num(seed);
std::uniform_int_distribution<long long> range(0, 10);
long long a = range(rand_num);
long long b = rand_num();
std::cout<<seed<<"\n"; // the seed is different every time (tested)
std::cout<<a<<"\n";
std::cout<<b<<"\n";
system("pause");
return 0;
}
The one with std::uniform_int_distribution (a) isn't random when running the code on my own computer but works ok and creates a random number on the online IDEs. 具有std :: uniform_int_distribution(a)的那个在我自己的计算机上运行代码时不是随机的,但是可以正常工作并在在线IDE上创建一个随机数。
The one without std::uniform_int_distribution (b) works ok with both online IDEs and my own computer. 没有std :: uniform_int_distribution(b)的那个适用于在线IDE和我自己的计算机。
What's the problem? 有什么问题? How can I fix it?
我该如何解决?
UPDATE: The code works ok with mt19937 engine (std::mt19937 and std::mt19937_64) 更新:代码适用于mt19937引擎(std :: mt19937和std :: mt19937_64)
It seems to be a known problem of g++ implementation on Windows. 这似乎是Windows上g ++实现的一个已知问题。 See the accepted answer to a similar question: Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?
请参阅类似问题的已接受答案: 为什么我使用mingw gcc4.8.1使用std :: random_device进行每次运行都会得到相同的序列?
To avoid the problem you can use <chrono>
facilities to seed the random number generator: 为避免此问题,您可以使用
<chrono>
工具为随机数生成器播种:
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
srand(time(0));
long long seed = rand();
std::default_random_engine rand_num{static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())};
// ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
std::uniform_int_distribution<long long> range{1,10};
long long a = range(rand_num);
long long b = rand_num();
std::cout<<seed<<"\n"; // the seed is different every time (tested)
std::cout<<a<<"\n";
std::cout<<b<<"\n";
system("pause");
return 0;
}
This gave me different results at every run ( with g++ on Windows). 这给了我每次运行时的不同结果(在Windows上使用g ++)。
Your code works fine with Visual C++, but fails for me with g++ 5.2.0. 您的代码在Visual C ++中运行良好,但对于我来说,使用g ++ 5.2.0失败了。 It looks to me like a bug in gcc's standard library.
它看起来像是gcc标准库中的一个错误。
Yet more evidence that using the default_random_engine
is just a bad idea in general, and using time(0)
as a seed is pretty awful as well (though a quick check indicates that changing it to use random_device
for the seed still produces broken results). 更多证据表明,使用
default_random_engine
通常只是一个坏主意,并且使用time(0)
作为种子也非常糟糕(尽管快速检查表明将其更改为使用random_device
进行种子仍会产生破碎的结果)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.