random随机数模块
在人工智能或数据处理时,我们经常会遇到随机数,还有seed()函数,这些内容属于标准库中random模块。
random随机数模块
random() 方法返回随机生成的一个实数,它在[0,1)范围内。
示例如下
import random
print(random.random())
第一次运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t42.py
0.6229016948897019
Process finished with exit code 0
第二次运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t42.py
0.0037590623342890206
Process finished with exit code 0
seed() 函数让随机失效
seed(n) 函数可以让随机失效,即每次随机的结果相同。相同的n,随机结果相同,不同的n,随机结果不同。
这个函数需要在随机函数之前调用。
示例如下
import random
random.seed(5)
print(random.random())
random.seed(10)
print(random.random())
第一次运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t42.py
0.6229016948897019
0.5714025946899135
Process finished with exit code 0
第二次运行结果(与第一次相同)
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t42.py
0.6229016948897019
0.5714025946899135
Process finished with exit code 0