我得到一个用 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/urandom
或RDRND
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/