为什么<random>库在使用 std::uniform_int_distribution 时每次都产生相同的结果
Why is <random> library producing the same results every time when using std::uniform_int_distribution
备注:
- 我的编译器是g++5.1.0-2,采用c++14语言标准
- 我的IDE是Code::Blocks(我也在Dev-C++上尝试过代码)
- 我测试代码的在线IDE是http://cpp.sh/(C++外壳)和https://www.codechef.com/ide(CodeChef.com的IDE)均运行c++14
- 当使用在线IDE时,代码运行良好,这让我更加困惑
这是代码:
#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::mt19937和std::mt 19937_64)配合良好
这似乎是Windows上g++实现的一个已知问题。请参阅类似问题的公认答案:为什么每次使用std::random_device和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++)。
您的代码在Visual C++中运行良好,但在g++5.2.0中失败了。在我看来,它就像是gcc标准库中的一个bug。
然而,更多的证据表明,使用default_random_engine
通常是个坏主意,而使用time(0)
作为种子也相当糟糕(尽管快速检查表明,将其更改为使用random_device
作为种子仍然会产生坏结果)。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何让C++'tally up'结果并制定计划?
- 为什么这个程序的结果是3 "born"?和 4 死
- 尝试将字符串/字符转换为整数会产生意外结果