为什么NumPy不允许字符串种子,而Random库在Python中允许它



在Python中使用random库时,我可以执行以下操作

>>> import random
>>> random.seed("twenty five")

但是如果我使用NumPy生成随机数,我就不能用字符串设置种子

>>> import numpy as np
>>> np.random.seed("twenty five")
Traceback (most recent call last):
File "_mt19937.pyx", line 178, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: 'str' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 244, in numpy.random.mtrand.RandomState.seed
File "_mt19937.pyx", line 166, in numpy.random._mt19937.MT19937._legacy_seeding
File "_mt19937.pyx", line 186, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: Cannot cast scalar from dtype('<U11') to dtype('int64') according to the rule 'safe'

NumPy是否可以接受字符串作为种子?

如果没有,是否有正确的方法将字符串转换为int以在NumPy中设置种子?

random库的seed函数背后的机制是什么,使其能够接受字符串种子?

https://docs.python.org/3/library/random.html

从python文档,

random.seed(a=None, version=2)

在版本2(默认(中,str、字节或字节数组对象将转换为int,并使用其所有位。

这意味着"twenty five"没有转换为25,而是通过其ascii表示(以及Tim Roberts在评论中指出的SHA512摘要(。

请注意,此功能现已弃用。

编辑:

源代码

elif version == 2 and isinstance(a, (str, bytes, bytearray)):
if isinstance(a, str):
a = a.encode()
a = int.from_bytes(a + _sha512(a).digest(), 'big')

最新更新