【发布时间】:2015-12-20 06:13:48
【问题描述】:
下面的代码旨在生成区间 [1,100] 中的五个伪随机数的列表。我用time(0) 为default_random_engine 播种,它在unix time 中返回系统时间。当我使用 Microsoft Visual Studio 2013 在 Windows 7 上编译和运行该程序时,它按预期工作(见下文)。但是,当我在 Arch Linux 中使用 g++ 编译器执行此操作时,它的行为很奇怪。
在 Linux 中,每次会生成 5 个数字。最后 4 个数字在每次执行时都会有所不同(通常情况如此),但第一个数字将保持不变。
在 Windows 和 Linux 上执行 5 次的示例输出:
| Windows: | Linux:
---------------------------------------
Run 1 | 54,01,91,73,68 | 25,38,40,42,21
Run 2 | 46,24,16,93,82 | 25,78,66,80,81
Run 3 | 86,36,33,63,05 | 25,17,93,17,40
Run 4 | 75,79,66,23,84 | 25,70,95,01,54
Run 5 | 64,36,32,44,85 | 25,09,22,38,13
更神秘的是,第一个数字在 Linux 上会周期性地加一。得到上述输出后,我等了大约30分钟,再次尝试发现第一个数字变了,现在一直生成为26。它周期性地继续递增1,现在是32。似乎对应time(0) 的值变化。
为什么第一个数字在运行过程中很少改变,然后当它改变时,增加 1?
代码。它整齐地打印出 5 个数字和系统时间:
#include <iostream>
#include <random>
#include <time.h>
using namespace std;
int main()
{
const int upper_bound = 100;
const int lower_bound = 1;
time_t system_time = time(0);
default_random_engine e(system_time);
uniform_int_distribution<int> u(lower_bound, upper_bound);
cout << '#' << '\t' << "system time" << endl
<< "-------------------" << endl;
for (int counter = 1; counter <= 5; counter++)
{
int secret = u(e);
cout << secret << '\t' << system_time << endl;
}
system("pause");
return 0;
}
【问题讨论】:
-
sizeof(time_t)与sizeof(default_random_engine::result_type)是什么? -
请注意,
default_random_engine在这两个平台上完全不同。 -
它仍然可以是随机的 BTW。
-
是否每个程序员都经历过他们认为时间是一个很好的随机数生成器种子的阶段?
-
@OldFart 是的,这叫学术界。
标签: c++ linux windows gcc visual-studio-2013