使用C ++ 11随机库生成随机数 [英] Generate random numbers using C++11 random library
问题描述
正如标题所示,我试图找到一种使用新的C ++ 11 <random>
库生成随机数的方法.我已经用以下代码尝试过:
As the title suggests, I am trying to figure out a way of generating random numbers using the new C++11 <random>
library. I have tried it with this code:
std::default_random_engine generator;
std::uniform_real_distribution<double> uniform_distance(1, 10.001);
我的代码存在的问题是,每次我编译并运行它时,它总是生成相同的数字.所以我的问题是,在真正随机的情况下,随机库中还有哪些其他函数可以完成此任务?
The problem with the code I have is that every time I compile and run it, it always generates the same numbers. So my question is what other functions in the random library can accomplish this while being truly random?
对于我的特定用例,我试图获取一个在[1, 10]
For my particular use case, I was trying to get a value within the range [1, 10]
推荐答案
Microsoft的Stephan T. Lavavej(stl)在Going Native上发表了关于如何使用新的C ++ 11随机函数以及为什么不使用rand()
.在其中,他包括一张幻灯片,该幻灯片基本上可以解决您的问题.我已经从下面的幻灯片中复制了代码.
Stephan T. Lavavej (stl) from Microsoft did a talk at Going Native about how to use the new C++11 random functions and why not to use rand()
. In it, he included a slide that basically solves your question. I've copied the code from that slide below.
您可以在此处查看他的完整讲话: http://channel9. msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
You can see his full talk here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(1.0, 10.0);
for (int i=0; i<16; ++i)
std::cout << dist(mt) << "\n";
}
我们使用random_device
一次来播种名为mt
的随机数生成器. random_device()
比mt19937
慢,但是不需要种子,因为它会从您的操作系统中请求随机数据(该数据将来自各个位置,例如
We use random_device
once to seed the random number generator named mt
. random_device()
is slower than mt19937
, but it does not need to be seeded because it requests random data from your operating system (which will source from various locations, like RdRand for example).
查看此问题/答案,看来uniform_real_distribution
返回了您要在[a, b]
范围内的[a, b)
范围内的数字.为此,我们的uniform_real_distibution
实际上应如下所示:
Looking at this question / answer, it appears that uniform_real_distribution
returns a number in the range [a, b)
, where you want [a, b]
. To do that, our uniform_real_distibution
should actually look like:
std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));
这篇关于使用C ++ 11随机库生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!