std :: random_device和std :: mt19937是否遵循均匀分布? [英] Do std::random_device and std::mt19937 follow an uniform distribution?

查看:447
本文介绍了std :: random_device和std :: mt19937是否遵循均匀分布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C ++中转换matlab的这一行:rp = randperm(p);

I'm trying to convert this line of matlab in C++: rp = randperm(p);

遵循randperm 文档:

randperm使用与rand相同的随机数生成器

randperm uses the same random number generator as rand

并且在rand 页面:

rand返回一个均匀分布的随机数

rand returns a single uniformly distributed random number

因此,rand遵循均匀分布.我的C ++代码基于:

So rand follows an uniform distribution. My C++ code is based on:

std::random_device rd;
std::mt19937 g(rd());
std::shuffle(... , ... ,g);

我的问题是:上面的代码遵循均匀分布?如果没有,该怎么办?

My question is: the code above follows an uniform distribution? If not, how to do so?

推荐答案

C ++随机数库不同的类大致如下:

  • std::random_device 分布均匀的随机数生成器,可以访问系统中的硬件设备,或者在Linux上类似于/dev/random之类的东西.由于底层设备通常会很快耗尽熵,因此通常仅将其用作伪随机生成器的种子.
  • std::mt19937 是使用Merenne Twister引擎,根据原始作者的论文标题,该引擎也是统一的.这将生成完全随机的32位或64位无符号整数.由于std::random_device仅用于为该生成器提供种子,因此它自身不必一定是统一的(例如,您经常使用当前时间戳(绝对不是均匀分布的)来为生成器提供种子.
  • 通常,您使用生成器(例如std::mt19937)来馈送特定的发行版,例如 std::uniform_int_distribution std::shuffle
  • std::random_device is a uniformly-distributed random number generator that may access a hardware device in your system, or something like /dev/random on Linux. It is usually just used to seed a pseudo-random generator, since the underlying device wil usually run out of entropy quickly.
  • std::mt19937 is a fast pseudo-random number generator using the Mersenne Twister engine which, according to the original authors' paper title, is also uniform. This generates fully random 32-bit or 64-bit unsigned integers. Since std::random_device is only used to seed this generator, it does not have to be uniform itself (e.g., you often seed the generator using a current time stamp, which is definitely not uniformly distributed).
  • Typically, you use a generator such as std::mt19937 to feed a particular distribution, e.g. a std::uniform_int_distribution or std::normal_distribution which then take the desired distribution shape.
  • std::shuffle, according to the documentation,

对给定范围[first, last)中的元素进行重新排序,以使这些元素的每个可能排列具有相同的出现概率.

Reorders the elements in the given range [first, last) such that each possible permutation of those elements has equal probability of appearance.

在您的代码示例中,您使用std::mt19937 PRNG来馈送std::shuffle.因此,std::mt19937是统一的,并且std::shuffle也应具有统一的行为.因此,一切都尽可能统一.

In your code example, you use the std::mt19937 PRNG to feed std::shuffle. So, std::mt19937 is uniform, and std::shuffle should also behave uniformly. So, everything is as uniform as it can be.

这篇关于std :: random_device和std :: mt19937是否遵循均匀分布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆