为什么在我按时间播种发电机的同时,我会保持相同的第一位数字?

Ric*_*ick 27 c++

我不明白为什么我总是收到相同的第1位的时候我已经接种于default_random_enginetime(0)(C++入门告诉我用time(0)).这是我的电脑的问题吗?(Ubuntu,C++ 11)

我尝试了一个在线编译器,有趣的是我使用了相同的第一个数字gcc而不使用clang++.

https://wandbox.org/permlink/kiUg1BW1RkDL8y8c

码:

#include <iostream>
#include <ctime>
#include <random>
using namespace std;
int main(){
    auto t = time(0);
    cout << "time: " << t << endl;
    default_random_engine e(t);
    uniform_int_distribution<int> uniform_dist(0, 9);
    cout << "sequence:";
    for(int i = 0; i < 10; i++){
        cout << uniform_dist(e);
    }
    cout << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

正如你所看到的6,无论我使用clang++还是g++编译,我都会随机获得一个随机数的第一个数字. 在此输入图像描述

Whe*_*zil 29

您正在将初始状态设置为非常相似的随机生成器.根据发电机的质量,这可能会也可能不会产生类似的输出.为了说明,我已经将您的样本扩充到(a)只打印第一个序列,因为这是我们关心的,并且(b)打印出各种分辨率的几个结果:

int main(){
    auto t = time(0);
    cout << "time: " << t << endl;
    default_random_engine e(t);
    default_random_engine e2(t);
    default_random_engine e3(t);
    default_random_engine e4(t);
    uniform_int_distribution<int> uniform_dist(0, 9);
    uniform_int_distribution<int> uniform_dist2(0,999);
    uniform_int_distribution<int> uniform_dist3(0,99999);
    uniform_int_distribution<int> uniform_dist4(0,9999999);
    cout << "sequence: ";
    cout << uniform_dist(e) << " " << uniform_dist2(e2) << " " << uniform_dist3(e3) << " " << uniform_dist4(e4);
    cout << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行时:

$ ./a.out
time: 1541162210
sequence: 7 704 70457 7070079
$ ./a.out
time: 1541162211
sequence: 7 704 70457 7070157
$ ./a.out
time: 1541162212
sequence: 7 704 70458 7070236
$ ./a.out
time: 1541162213
sequence: 7 704 70459 7070315
$ ./a.out
time: 1541162214
sequence: 7 704 70460 7070393
$ ./a.out
time: 1541162215
sequence: 7 704 70461 7070472
$ ./a.out
time: 1541162216
sequence: 7 704 70461 7070550
$ ./a.out
time: 1541162217
sequence: 7 704 70462 7070629
$ ./a.out
time: 1541162218
sequence: 7 704 70463 7070707
$ ./a.out
time: 1541162219
sequence: 7 704 70464 7070786
Run Code Online (Sandbox Code Playgroud)

虽然我不确切知道这个随机生成器实现在做什么,但您可以很容易地看到它正在执行一个非常简单的种子转换为状态,并将状态转换为输出值.正如其他评论所暗示的那样,有更好的随机生成器和更好的种子.另请注意,质量因实施而异; Visual Studio 2017不会出现此行为.

  • 老兄,这个实验是如此聪明和坦率.非常全面,谢谢. (2认同)