C++ 11 随机数生成不起作用

C++ 11 random number generation not working

//My trial program
#include<iostream>
#include<random>

using namespace std;

int main(){

    //USed to initialize (seed) the random number generator
    random_device sd{};

    // The random number generator
    mt19937 engine {sd()};

    //Uniformly distribute random numbers in [1...10]
    uniform_int_distribution <> dis{1, 50};

    //Generate a random integer
    int x {dis(engine)};

    //Print it 

    cout<<x<<"\n";

    return 0;

}

我已经使用上面的代码生成了 1 到 50 之间的随机数。但是每当我 运行 程序时,生成的随机数都是相同的。我正在参加的在线课程有这段代码,它在讲师的 clang 编译器上运行得非常好。我正在使用 gcc 编译器。谁能告诉我需要做什么?谢谢!!

这里的问题是 std::random_device 不必真的是随机设备。它可以是未播种 rand 的包装器,每次使用它时都会给你相同的值。这意味着您的 engine 种子将是相同的,这意味着它生成的伪随机序列也将是相同的。

解决这个问题的一种方法是使用电流作为种子,例如

auto seed = std::chrono::system_clock::now().time_since_epoch().count();
mt19937 engine {seed};

但这可以通过外部进程进行操作,并且粒度不是很细,因此同时播种的多个实例都可以生成相同的序列。

来自 std::random_device :

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

虽然对于它的用户而言并不理想,但允许实现具有您描述的行为。