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 随机库生成随机数
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
