备注:
以下是代码:
#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;
}在我自己的计算机上运行代码时,带有std::uniform_int_distribution (a)的代码不是随机的,但是工作正常,并在在线IDE上创建一个随机数。
没有std::uniform_int_distribution (b)的那个可以在在线IDE和我自己的电脑上正常工作。
有什么问题吗?我怎么才能修好它?
更新:代码在mt19937引擎中工作正常(std::ok 19937和std::mt19937_64)
发布于 2016-01-08 17:32:03
这似乎是g++在Windows上实现的一个已知问题。参见对类似问题的公认答案:device with mingw gcc4.8.1?
为了避免这个问题,可以使用<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;
}这在每次运行时给了我不同的结果(在Windows上使用g++ )。
发布于 2016-01-08 16:38:01
您的代码在VisualC++中运行良好,但对于我来说,g++ 5.2.0却失败了。在我看来,它就像gcc标准图书馆里的一个bug。
然而,更多的证据表明,使用default_random_engine一般只是一个糟糕的想法,而使用time(0)作为种子也是相当糟糕的(尽管快速检查表明,将其更改为对种子使用random_device仍然会产生坏结果)。
https://stackoverflow.com/questions/34680805
复制相似问题