隨機數種子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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM