为什么python随机。对非估计输入的非确定性分析?

发布于 2025-01-31 22:42:14 字数 478 浏览 3 评论 0原文

Python 3.8上的以下代码始终打印18(我已经在3台不同的机器上尝试过):

import random
random.seed(1)
print(random.randint(1, 100))

但是,在Python 3.8中使用非概念的种子是半否定的:

import random
from datetime import date
random.seed(date(2022, 5, 18))
print(random.randint(1, 100))

我说半决赛,因为如果我运行代码多个代码在相同的Python过程(例如Python终端)中,我得到相同的随机数。但是,但是如果我重新启动Python过程,我会得到不同的数字。

显然,它不使用对象的id,因为每次我制作新的日期对象时,我都不会在Python终端中获得相同的结果。

那么,发生了什么?

The following code on Python 3.8 always prints 18 (I've tried this on 3 different machines):

import random
random.seed(1)
print(random.randint(1, 100))

However, calling seed with a non-primative in Python 3.8 is semi-nondeterministic:

import random
from datetime import date
random.seed(date(2022, 5, 18))
print(random.randint(1, 100))

I say semi-nondeterministic because if I run the code multiple times within the same Python process (such as a Python terminal), I get the same random number. However, but if I restart the Python process, I get a different number.

Clearly it's not using id of the object, since that changes every time I make a new date object so I wouldn't get the same result within a Python terminal.

What, then, is going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

坦然微笑 2025-02-07 22:42:14

使用种子与非类型,int,float,str,bytes或bytearray以外的其他类型使用,从python 3.9开始弃用,这可能是由于这种行为所致。

通过将日期投入到字符串,代码成为确定性。以下代码始终打印46:

import random
from datetime import date
random.seed(str(date(2022, 5, 18)))
print(random.randint(1, 100))

引擎盖下的情况可能是seed使用复杂对象的哈希。以下代码的行为与将日期传递给seed的行为相同,即,结果在单个Python过程中是确定性的,但在Python过程之间有所不同:

from datetime import date
print(hash(date(2022, 5, 18)))

请注意,random.seed.seed.seed从字面上看hash,由于以下结果(99%的时间):

random.seed(date(2022, 5, 18))
a = random.randint(1, 100)

random.seed(hash(date(2022, 5, 18)))
b = random.randint(1, 100)
print(a, b)

Using seed with types other than NoneType, int, float, str, bytes, or bytearray is deprecated starting in Python 3.9, likely due to this behavior.

By casting a date to a string, the code becomes deterministic. The following code always prints 46:

import random
from datetime import date
random.seed(str(date(2022, 5, 18)))
print(random.randint(1, 100))

What is going on under the hood is likely that seed is using a hash of the complex object. The following code has the same behavior as passing a Date to seed, namely that it's result is deterministic within a single Python process but different between Python processes:

from datetime import date
print(hash(date(2022, 5, 18)))

Note that random.seed doesn't literally use hash, since the following gives different results (99% of the time):

random.seed(date(2022, 5, 18))
a = random.randint(1, 100)

random.seed(hash(date(2022, 5, 18)))
b = random.randint(1, 100)
print(a, b)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文