python random.seed(),初始化随机数生成器种子

random.seed()方法

在python中,在调用random.random()方法时如果要得到两个相同的随机数,那该怎么办呢?可以是用Python标准库random中的seed()方法,初始化一个随机数生成器种子,其语法如下:


语法

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

python中关于random.seed()的源码如下:

seed(a=None, version=2) method of random.Random instance
    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.

1、当seed()方法中的第一个参数a值为None或不传递的情况下,系统将根据时间来选择a的值;2、version参数为版本,默认为2。

random.seed()方法实例代码

>>> import random
>>> random.random()
0.944276384533455
>>> random.random()
0.7971996146734703
>>> random.seed(1) #调用该方法生成随机数生成器种子
>>> random.random()
0.13436424411240122
>>> random.random()
0.8474337369372327
>>> random.seed(1) #重新调用该随机数生成器种子
>>> random.random()
0.13436424411240122

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.