C ++ std :: mt19937和ng状态保存/加载和加载可移植性 [英] C++ std::mt19937 and rng state save/load & portability

查看:247
本文介绍了C ++ std :: mt19937和ng状态保存/加载和加载可移植性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够保存和加载RNG的状态,以便可以从给定的点重现相同的随机值(应用程序保存/快照).

我看到有一个运算符<<和>>重载,它似乎可以作为数字序列保存到字符串中.

  • 这是最好/唯一的保存方式吗?我不介意仅使用固定大小的二进制状态值,而不是用空格分隔的字符串,然后再为文件格式添加前缀或定界符.
  • 这是所有便携式产品吗?例如我可以在不同的编译器版本之间,甚至在MSVC和GCC之间转移它,以在给定相同配置的分布情况下生成相同的数据集(对于浮点数,误差很小,对于整数数学精确)?

解决方案

是的,operator<<operator>>是导入或导出随机数生成器状态的唯一方法.如果需要,您可以轻松地将文本表示形式与二进制进行转换.

mt19937状态进行反序列化和序列化应该在实现之间可移植.只要您确保流具有相同的语言环境,就可以通过标准很好地定义通过流运算符读取和写入引擎状态的结果.

关于operator<<operator>>的要求,请参见§26.5.1.5,随后是关于>的文本表示的§26.5.3.2,其中mt19937是定义明确的的.

I want to be able to save and load the state of an RNG so I can reproduce the same random values from a given point (application save/snapshot).

I see there is an operator << and >> overload, which seems to save to a string as a sequence of numbers.

  • Is that the best/only way to save? I wouldn't mind just having the fixed-size binary state value not this space separated string thing that I then need to prefix or put delimiters around for my file format.
  • Is this at all portable? e.g. can I transfer this between different compiler versions, or even between MSVC and GCC to produce the same data set given identically configured distributions (to a small margin of error in the case of floating point, and exact for integer maths)?

解决方案

Yes, operator<< and operator>> are the only way to import or export a random number generator's state. You can easily convert the textual representation to and from binary, if you'd like.

De-serializing and serializing mt19937 state should be portable between implementations. The result of reading and writing the engine's state via the streaming operators is well defined by the standard, as long as you ensure the streams are imbued with the same locale.

See § 26.5.1.5 for the requirements of operator<< and operator>>, followed by § 26.5.3.2 for the textual representation of mersenne_twister_engine, which mt19937 is a well defined typedef of.

这篇关于C ++ std :: mt19937和ng状态保存/加载和加载可移植性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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