如何生成可重复的随机数序列? [英] How to generate a repeatable random number sequence?

查看:173
本文介绍了如何生成可重复的随机数序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以生成值的伪随机序列的函数,但是该序列在每次运行时都可以重复。我想要的数据必须合理地随机分布在给定的范围内,而不必是完美的。

I would like a function that can generate a pseudo-random sequence of values, but for that sequence to be repeatable every run. The data I want has to be reasonably well randomly distributed over a given range, it doesn't have to be perfect.

我想编写一些具有性能的代码根据随机数据对其进行测试。我希望每台机器上的每个测试运行的数据都是相同的,但是由于存储的原因,我不想随测试一起运送随机数据(最终可能会变成许多兆字节)。

I want to write some code which will have performance tests run on it, based on random data. I would like that data to be the same for every test run, on every machine, but I don't want to have to ship the random data with the tests for storage reasons (it might end up being many megabytes).

random 模块的库似乎没有说相同的种子在任何机器上总是给出相同的顺序

The library for the random module doesn't appear to say that the same seed will always give the same sequence on any machine.

编辑:如果您要建议我对数据进行播种(如上所述),请提供证明该方法有效且可用于的文件。一系列机器/实现。

If you're going to suggest I seed the data (as I said above), please provide the documentation that says the approach valid, and will work on a range of machines/implementations.

编辑:Mac OS X上的CPython 2.7.1和PyPy 1.7以及CPython 2.7.1和CPython 2.52 = .2 Ubuntu似乎给出了相同的结果。仍然没有任何文档以黑白显示。

CPython 2.7.1 and PyPy 1.7 on Mac OS X and CPython 2.7.1 and CPython 2.52=.2 Ubuntu appear to give the same results. Still, no docs that stipulate this in black and white.

有什么想法吗?

推荐答案

文档未明确指出提供种子将始终保证相同的结果,但这可以通过Python基于所使用算法的随机实现来保证。

The documentation does not explicitly say that providing a seed will always guarantee the same results, but that is guaranteed with Python's implementation of random based on the algorithm that is used.

根据文档,Python使用 Mersenne Twister 作为核心生成器。播种此算法后,它不会获得任何外部输出,因此不会更改后续调用,因此给它相同的种子,您获得相同的结果。

According to the documentation, Python uses the Mersenne Twister as the core generator. Once this algorithm is seeded it does not get any external output which would change subsequent calls, so give it the same seed and you will get the same results.

当然,您也可以通过设置种子并生成大数量的随机数并验证它们是否相同来观察到这一点,但是我知道不想独自相信它。

Of course you can also observe this by setting a seed and generating large lists of random numbers and verifying that they are the same, but I understand not wanting to trust that alone.

除了CPython之外,我还没有检查其他Python实现,但是我非常怀疑它们会使用完全不同的算法来实现随机模块。

I have not checked that other Python implementations besides CPython but I highly doubt they would implement the random module using an entirely different algorithm.

这篇关于如何生成可重复的随机数序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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