种子 python 随机在 Mac 和 Windows 上产生不同的数字

发布于 2024-11-19 03:18:46 字数 572 浏览 5 评论 0原文

我参与了一个将在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

禾厶谷欠 2024-11-26 03:18:46

您是否有可能使用两个不同版本的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.

铜锣湾横着走 2024-11-26 03:18:46

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文