在C ++中生成随机数 [英] generate random number in c++

查看:217
本文介绍了在C ++中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个在c ++中生成数万个随机数的任务.我已经在c ++上搜索了很多有关随机数的内容,并查找了c ++参考,但是现在我很困惑.

I get a task to generate tens of thousands random number in c++. I've googled a lot about random number in c++ and look up the c++ reference, but I got confused now.

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

As I know, random_device is a non-deterministic random number generator, but every time I re-run my program, the random number generated by random_device is the same. So how do I set a seed for random_device to make the random number is different when I restart my program?

我读到如果您尝试从中获取很多数字,std :: random_device可能会用尽熵.这可能会导致其阻塞,直到您移动鼠标或其他东西为止".这意味着我的程序可能会在某些时候暂停.我如何避免这种情况发生?

And I've read that "std::random_device could run out of entropy if you try to get a lot of numbers from it. That could cause it to block until you move the mouse or something". That means my program could pause at some time. How can I avoid this happening?

推荐答案

来自在这里,您可以看到std::random_device并不总是保证不确定性:

From here, you can see std::random_device does not always guarantee to be non-deterministic:

std :: random_device可以用实现定义的伪随机数引擎实现,如果不确定的源(例如硬件设备)对实现不可用.在这种情况下,每个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指令"nofollow noreferrer>此处:

On Linux, it by default uses /dev/urandom or RDRND CPU instruction according to here:

libc ++和libstdc ++中的实现期望令牌是字符设备的名称,该字符设备在读取时会产生随机数,其默认值为"/dev/urandom" ,尽管其中CPU指令RDRND可用,libstdc ++使用它作为默认指令.

不会阻止.您可以使用方法此处切换到安全的设备/dev/random ,但是如果没有足够的熵,该设备将被阻止.

which won't block. You can switch to a even secured device /dev/random using approach here, but that device will block if not having enough entropy.

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

On Windows, I'm not sure about such device therefore it might fall back to some PRNG which requires some kind of seed.

要跨平台解决问题,如@Binara所述,可以使用<cstdlib>中的std::rand.此功能不会被阻止,您可以使用std::srand(somethingLikeCurrentTime)使其具有不确定性.

To solve the problem cross-platformly, as @Binara mentioned, you can use std::rand from <cstdlib>. This function will not block, and you can use std::srand(somethingLikeCurrentTime) to make it some-what non-deterministic.

如@ user1118321所述,如果要使用更安全的PRNG,则可以考虑std::mersenne_twister_engine并使用std::random_device生成它的种子.建议在此处.

As @user1118321 mentioned, if you want to use a more secured PRNG, you might consider std::mersenne_twister_engine and use std::random_device to generate a seed of it. This approach is suggested here.

这篇关于在C ++中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆