std::random_device 和 std::mt19937 服从均匀分布吗?
Do std::random_device and std::mt19937 follow an uniform distribution?
我正在尝试用 C++ 转换这行 matlab:rp = randperm(p);
继 randperm
documentation 之后:
randperm uses the same random number generator as rand
并且在 rand
page:
rand returns a single uniformly distributed random number
所以rand
服从均匀分布。我的 C++ 代码基于:
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(... , ... ,g);
我的问题是:上面的代码服从均匀分布?如果没有,怎么办?
不同于C++ random number library的类大致工作如下:
std::random_device
是一个 均匀分布的 随机数生成器,它可以访问您系统中的硬件设备,或者类似于 [=47 上的 /dev/random
=].它通常只用于为伪随机生成器播种,因为底层设备通常 运行 很快就会失去熵。
std::mt19937
is a fast pseudo-random number generator using the Mersenne Twister engine按照原作者的论文题目,也是统一的。这会生成完全随机的 32 位或 64 位无符号整数。由于 std::random_device
仅用于为该生成器播种,因此它本身不必是统一的(例如,您经常使用当前时间戳为生成器播种,这绝对不是均匀分布的)。
- 通常,您使用
std::mt19937
之类的生成器来提供特定的 分布 ,例如a std::uniform_int_distribution
or std::normal_distribution
然后采用所需的分布形状。
std::shuffle
,根据文档,
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
也应该表现统一。所以,一切都尽可能统一。
我正在尝试用 C++ 转换这行 matlab:rp = randperm(p);
继 randperm
documentation 之后:
randperm uses the same random number generator as rand
并且在 rand
page:
rand returns a single uniformly distributed random number
所以rand
服从均匀分布。我的 C++ 代码基于:
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(... , ... ,g);
我的问题是:上面的代码服从均匀分布?如果没有,怎么办?
不同于C++ random number library的类大致工作如下:
std::random_device
是一个 均匀分布的 随机数生成器,它可以访问您系统中的硬件设备,或者类似于 [=47 上的/dev/random
=].它通常只用于为伪随机生成器播种,因为底层设备通常 运行 很快就会失去熵。std::mt19937
is a fast pseudo-random number generator using the Mersenne Twister engine按照原作者的论文题目,也是统一的。这会生成完全随机的 32 位或 64 位无符号整数。由于std::random_device
仅用于为该生成器播种,因此它本身不必是统一的(例如,您经常使用当前时间戳为生成器播种,这绝对不是均匀分布的)。- 通常,您使用
std::mt19937
之类的生成器来提供特定的 分布 ,例如astd::uniform_int_distribution
orstd::normal_distribution
然后采用所需的分布形状。 std::shuffle
,根据文档,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
也应该表现统一。所以,一切都尽可能统一。