std::uniform_int_distribution的重复值

4

我不明白这里发生了什么。

#include <iostream>
#include <random>
#include <chrono>
using namespace std;

unsigned number_in_range(unsigned, unsigned, default_random_engine);

int main()
{

    time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());

    default_random_engine rng(now);

    //
    // Print out 10 random numbers
    //
    for (int i = 0; i < 10; i++)
    {
        uniform_int_distribution<int> dist(0, 100);
        cout << dist(rng) << endl;
    }

    cout << endl;

    //
    // Do the same thing, but get the numbers from `number_in_range()`
    //
    for (int i = 0; i < 10; i++)
    {
        cout << number_in_range(0, 100, rng) << endl;
    }

    return 0;
}

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine rng)
{
    uniform_int_distribution<int> dist(range_start, range_end);
    return dist(rng);
}

这段代码的输出示例如下:
45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68
< p > number_in_range() 与我第一个for循环中的代码完全相同,但它多次输出相同的值。 number_in_range() 版本有什么不同之处,我该如何修复它?

1个回答

14

您正在复制随机引擎而不是获取其引用。因此,它始终具有相同的内部状态。

尝试:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)

非常好。谢谢。 - Michael Dorst
顺便提一下,我注意到生成的第一个数字总是45。这正常吗?当我使用std::default_random_engine时,我应该总是取一个值并丢弃它吗? - Michael Dorst
@anthropomorphic 这是一个纯粹的种子问题。不要在不理解 PRNGs 的情况下丢弃东西。检查您的种子输入! - sascha
@T.C. 真的是这样。非常有启发性,谢谢。 - Michael Dorst

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接