使用C ++ 11随机库生成随机双精度数 [英] Generate random double 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 range within [1, 10]
推荐答案
来自Microsoft的Stephan T. Lavavej在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-有害
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
,但不需要进行播种,因为它从您的操作系统(它将从各种位置来源,例如 RdRand )。
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)
范围内的数字, code> [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屋!