看了某鸟上的教程,发现seed函数可以接受2个参数
但是使用时只有第一个参数有用,而第二个参数看起来像个摆设,请问为何要加入第二个参数
python seed函数
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
Lonelypatients° 2021-08-16 23:23关注For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds.翻译如下:
对于版本2(默认值),如果a是str,则使用所有位,
字节,或者bytearray。版本1(用于随机复制
str和的算法字节生成更窄的种子范围。也就是第二个参数值version, 不传时默认是2版本,
底层代码:def seed(self, a=None, version=2): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): a = a.decode('latin-1') if isinstance(a, bytes) else a x = ord(a[0]) << 7 if a else 0 for c in map(ord, a): x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a) a = -2 if x == -1 else x if version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a += _sha512(a).digest() a = int.from_bytes(a, 'big') super().seed(a) self.gauss_next = None也就是说不传时, a 也就是第一参数为是使用 字节或 bytearray类型,
传入 1时, 用于随机str 的算法字节生成更窄的种子范围。
从示例中可以看出:import random random.seed('100') print(random.random()) random.seed('100',1) print(random.random()) # 结果 0.35677737212581095 0.5211604367458436评论 打赏 举报解决 3无用