为什么python随机。对非估计输入的非确定性分析?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
种子
与非类型,int,float,str,bytes或bytearray以外的其他类型使用,从python 3.9开始弃用,这可能是由于这种行为所致。通过将日期投入到字符串,代码成为确定性。以下代码始终打印46:
引擎盖下的情况可能是
seed
使用复杂对象的哈希。以下代码的行为与将日期传递给seed
的行为相同,即,结果在单个Python过程中是确定性的,但在Python过程之间有所不同:请注意,
random.seed.seed.seed
从字面上看hash
,由于以下结果(99%的时间):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:
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 toseed
, namely that it's result is deterministic within a single Python process but different between Python processes:Note that
random.seed
doesn't literally usehash
, since the following gives different results (99% of the time):