种子 python 随机在 Mac 和 Windows 上产生不同的数字
我参与了一个将在 Mac 和 Windows 上运行的 python 应用程序,用 py2app 和 py2exe 打包成可执行文件。所有应用程序始终生成相同的随机数非常重要。所以随机模块总是得到相同的种子。
然而,random.shuffle() 的结果在 Windows 和 Mac 上似乎有很大不同。
有什么方法可以确保始终生成相同的随机数吗?
代码非常平淡:
import random
random.seed("ladygaga")
swaplist_odd = [n for n in range(len(clipboard)) if n % 2 != 0]
swaplist_even = [n for n in range(len(clipboard)) if n % 2 == 0]
random.shuffle(swaplist_odd)
random.shuffle(swaplist_even)
其想法是对缓冲区进行洗牌,并能够通过再次洗牌来重新创建原始缓冲区。
如果进程停留在一个操作系统内,就没有问题。一旦缓冲区文件被复制到另一个操作系统,原始文件的重新创建就会失败。
I am involved in a python application that will be running on Mac and Windows, packed into executables with py2app and py2exe. It is important that all apps generate the same random numbers at all times. So the random module always gets the same seed.
However, the outcomes of random.shuffle() seem to be very different on Windows an Mac.
Is there any way to make sure the same random numbers are always generated?
Code is very unexciting:
import random
random.seed("ladygaga")
swaplist_odd = [n for n in range(len(clipboard)) if n % 2 != 0]
swaplist_even = [n for n in range(len(clipboard)) if n % 2 == 0]
random.shuffle(swaplist_odd)
random.shuffle(swaplist_even)
The idea is to shuffle a buffer, and be able to recreate the original buffer by shuffling again.
If the process stays within one operating system, there is no problem. As soon as the buffer files are copied to another operating system, the re-creation of the original fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否有可能使用两个不同版本的Python?
根据 文档,Python 从使用 Wichmann-Hill 算法转向使用 Mersenne Twister从 2.3 开始生成伪随机数。
Is it possible that you're using two different versions of Python?
According to the documentation, Python moved from using the Wichmann-Hill algorithm to using the Mersenne Twister to generate pseudo-random numbers starting at 2.3.
Python 2.x 和 Python 3.x 似乎具有不兼容的随机数生成器,即使使用相同的数字作为种子,也会返回不同的结果。
对我来说,MacOS 上的 Python 2.7.16 返回与 Ubuntu 上的 Python 2.7.12 相同的结果。
MacOS 上的 Python 3.7.3 返回与 Ubuntu 上的 Python 3.5.2 相同的结果。
此外,字符串的哈希值在不同的 Python 安装上可能会有所不同,因此您应该使用数字种子而不是
ladygaga
。Python 2.x and Python 3.x seem to have incompatible random number generators and return different result even when seeded with the same number.
For me, Python 2.7.16 on MacOS returns the same as Python 2.7.12 on Ubuntu.
Python 3.7.3 on MacOS returns the same as Python 3.5.2 on Ubuntu.
Moreover, hash of a string can be different on different Python installations, so you should be using a numeric seed instead of
ladygaga
.