gpt4 book ai didi

c++ - 在C++中生成随机数

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:17 25 4
gpt4 key购买 nike

我接到一个任务,要用 C++ 生成数万个随机数。我在 google 上搜索了很多关于 c++ 中的随机数并查找 c++ 引用资料,但我现在感到困惑。

据我所知,random_device 是一个非确定性随机数生成器,但每次我重新运行我的程序时,random_device 生成的随机数都是相同的。那么,如何为 random_device 设置种子,以便在我重新启动程序时使随机数不同?

而且我读到“如果您尝试从中获取大量数字,std::random_device 可能会耗尽熵。这可能会导致它阻塞,直到您移动鼠标或其他东西”。这意味着我的程序可能会在某个时候暂停。我怎样才能避免这种情况发生?

最佳答案

来自 here , 你可以看到 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.

在 Linux 上,它默认使用 /dev/urandomRDRND CPU 指令根据 here :

The implementations in libc++ and libstdc++ expect token to be the name of a character device that produces random numbers when read from, with the default value "/dev/urandom", although where the CPU instruction RDRND is available, libstdc++ uses that as the default.

不会阻塞。您可以切换到更安全的设备 /dev/random使用方法 here ,但如果没有足够的熵,该设备将阻塞。

在 Windows 上,我不确定这样的设备,因此它可能会退回到需要某种种子的某些 PRNG。

要跨平台解决问题,如@Binara 所述,您可以使用 std::rand来自 <cstdlib> .这个函数不会阻塞,你可以使用std::srand(somethingLikeCurrentTime)使其有些不确定。

如@user1118321 所述,如果您想使用更安全的 PRNG,您可以考虑 std::mersenne_twister_engine并使用 std::random_device生成它的种子。建议使用此方法here .

关于c++ - 在C++中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773075/

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