随机数种子random.seed()理解

总结:

若采用random.random(),每次都按照一定的序列(默认的某一个参数)生成不同的随机数。

若采用随机数种子random.seed(100),它将在所设置的种子100范围内调用random()模块生成随机数,如果再次启动random.seed(100),它则按照之前的序列从头开始生成随机数,两次生成的随机序列相同。

若采用random.seed(),它则按照默认的一个序列生成随机数。

程序演示:

# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 17:27:28 2019

@author: Mr.King
"""

import random
random.seed(100)
print("----------random.seed(100)-----------------")
print("The first random number: ", random.random())
print("The second random number: ", random.random())
print("The third random number: ", random.random())

random.seed(100)
print("----------再次调用random.seed(100)----------")
print("The fourth random number: ", random.random())
print("The fifth random number: ", random.random())

random.seed()
print("----------random.seed()--------------------")
print("The sixth random number: ", random.random())
print("The seventh random number: ", random.random())

运行结果:

----------random.seed(100)----------------------
The first random number: 0.1456692551041303
The second random number: 0.45492700451402135
The third random number: 0.7707838056590222
----------再次调用random.seed(100)----------
The fourth random number: 0.1456692551041303
The fifth random number: 0.45492700451402135
----------random.seed()---------------------------
The sixth random number: 0.20294571682496443
The seventh random number: 0.05551047377535656

猜你喜欢

转载自www.cnblogs.com/wzw0625/p/11813818.html