如何重置随机数引擎
How to reset a random number engine?
我正在尝试使用 C++11 方法来生成随机数:
#include <random>
#include <functional>
#include <iostream>
int main(int argc, char *argv[])
{
std::normal_distribution<double> normal(0, 1);
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(normal, engine);
int size = 2;
engine.seed(0);
normal.reset();
for (int i = 0; i < size; ++i)
std::cout << generator() << std::endl;
std::cout << std::endl;
engine.seed(1);
normal.reset();
for (int i = 0; i < size; ++i)
std::cout << generator() << std::endl;
std::cout << std::endl;
engine.seed(0);
normal.reset();
for (int i = 0; i < size; ++i)
std::cout << generator() << std::endl;
return 0;
}
输出为:
0.13453
-0.146382
0.46065
-1.87138
0.163712
-0.214253
这意味着第一个和第三个序列并不相同,即使它们以相同的数字播种。拜托,我做错了什么?是
std::normal_distribution<double>
只是一个数学意义上的函数(确定性地从 x 中产生 y)还是我错过了什么?如果它只是一个函数,重置方法实际上做了什么?
您正在绑定引擎和发行版,例如以下重置调用不会影响绑定函数。
解决方案是将引用绑定到引擎和发行版
auto generator = std::bind(std::ref(normal), std::ref(engine));
您遇到的问题是std::bind
. std::bind
复制其论点。std::bind
制作副本的原因是,当参数可能不再存在时,该函数将在将来的某个未知时间点被调用。这意味着您对engine.seed()
等的调用是无用的。使用 std::ref
您可以通过引用绑定参数,这将为您提供预期的输出。
auto generator = std::bind(std::ref(normal), std::ref(engine));
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 当使用带有VS2019或VSCode的虚幻引擎4.24.2时,我如何修复这些错误的Intellisense错误
- Unity在虚幻引擎4中的"Vector3.Slerp"等效C++?
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 在虚幻引擎中删除NXOpen对象时崩溃
- 半随机数生成C++
- 程序在尝试猜测它选择的随机数时进入无限循环?
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- 如何为GSL(GNU科学库)调整C++式随机数引擎?
- 哪些C++随机数引擎具有 O(1) 丢弃功能
- C 11多个随机数引擎适配器
- Eigen::unaryExpr 和 const 用于随机数引擎
- 如何重置随机数引擎
- 指定的随机分布使用哪种类型的随机数引擎
- 当你复制一个随机数引擎和随机数分布时会发生什么?
- 用相同的引擎并行生成随机数是失败的
- 从多个线程访问随机数引擎