gpt4 book ai didi

c++ - 如何以安全便携的方式为随机数生成器播种?

转载 作者:行者123 更新时间:2023-12-03 17:50:06 25 4
gpt4 key购买 nike

背景:

,建议使用 std::random_device而不是播种随机数生成器的时间。如果我们看一下 related documentation ,我们可以读到:

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.



强调我的

现在让我们考虑以下示例:
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution distr(0, 9);

// Print a sequence of 10 uniformly distributed random integers
for(std::size_t i = 0; i < 10; ++i)
std::cout << distr(gen) << ' ';

return 0;
}

如果系统/平台不提供非确定性源,则该程序可能/将始终为每次运行生成相同的数字序列(在我的平台上实际上就是这种情况)。

在这种情况下, std::random_device比用当前时间播种随机数生成器要糟糕得多:
std::mt199937 gen(std::chrono::high_resolution_clock::now().time_since_epoch().count()); // time seed

问题:

我担心的是,如果有人想编写一个依赖于一些随机生成的数字的程序,并且需要:
  • 便于携带
  • 保证非确定性随机性

  • 然后 std::random_device不会是合适的。
    另一方面,始终使用时间种子将是一个非常令人沮丧的“解决方案”,因为如果给定平台有可用的不确定源, std::random_device然后会“更安全”。

    问题:

    我的问题分为两部分:
  • 用户空间
  • 有没有一种可移植的方法来检查当前平台上是否可以使用这种非确定性源?
  • 编译器端
  • 是否允许编译器替换 std::random_device如果主机平台没有可用的非确定性源,则按时间种子种子?或者标准中是否有某些内容会阻止这种替换?
  • 如果标准不禁止这种行为,编译器不实现它的原因是什么?


  • 也许这些应该是 2 或 3 个单独的问题。由于背景和问题很常见,我在同一篇文章中向他们询问了该主题的完整性。如果无论如何我必须将它们分成单独的问题,请告诉我。

    最佳答案

    Is there a portable way to check if such a non-deterministic source is available on the current platform?



    您可以使用 entropy std::random_device的成员函数检查源是否是不确定的。不幸的是,它不是 static constexpr函数,因此您必须使用常规的 if 语句,例如
    int main()
    {
    std::random_device rd;
    std::size_t seed;
    if (rd.entropy())
    seed = rd();
    else
    seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::mt19937 gen(seed);
    std::uniform_int_distribution distr(0, 9);

    // Print a sequence of 10 uniformly distributed random integers
    for(std::size_t i = 0; i < 10; ++i)
    std::cout << distr(gen) << ' ';

    return 0;
    }

    Are compilers allowed to replace std::random_device seeds by time seeds if the host platform has no non-deterministic source available ? Or is there something in the standard that would prevent such a replacement?



    这会改变程序的可观察行为,所以不,编译器不能这样做。

    关于c++ - 如何以安全便携的方式为随机数生成器播种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60454047/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com