Generate random numbers using C++11 random library(使用 C++11 随机库生成随机数)
问题描述
正如标题所暗示的,我试图找出一种使用新的 C++11
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]
推荐答案
来自微软的 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.
您可以在此处查看他的完整演讲::>
You can see his full talk here:
#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) << "
";
}
我们使用 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) 范围内的数字,其中您需要 [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 随机库生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C++11 随机库生成随机数
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
