使用 C++11 随机库生成随机数

Generate random numbers using C++11 random library(使用 C++11 随机库生成随机数)

本文介绍了使用 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 随机库生成随机数

基础教程推荐