在c中生成随机数
作者:互联网
我得到一个在c中生成成千上万个随机数的任务.我在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上,默认情况下根据here使用/ dev / urandom或RDRND CPU指令:
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.
这不会阻止.您可以使用方法here切换到安全的设备/ dev / random,但是如果没有足够的熵,该设备将被阻止.
在Windows上,我不确定这种设备,因此它可能会回落到需要某种种子的PRNG.
要跨平台解决问题,如@Binara所述,您可以使用< cstdlib>中的std :: rand.此函数不会被阻止,您可以使用std :: srand(somethingLikeCurrentTime)使其具有某种不确定性.
如@ user1118321所述,如果您想使用更安全的PRNG,则可以考虑std :: mersenne_twister_engine并使用std :: random_device生成它的种子.建议使用此方法here.
标签:random-seed,c,random 来源: https://codeday.me/bug/20191011/1895632.html