選擇你自己的 Python 冒險/隨機數和偽隨機數生成器
外觀
計算機如何生成隨機數?在自然現象的世界中,存在著(可能是)真正的隨機性來源,例如放射性衰變,但大多數計算機並不使用它們。相反,計算機依賴於產生偽隨機數的數學函式,稱為偽隨機數生成器 (PRNG)。
給定最後一個生成的數字和一些配置引數(統稱為狀態),它們會確定性地生成另一個數字。在一個好的 PRNG 中,這些數字會看起來不可預測,除非你瞭解“秘密配方”(生成器的狀態)。對於大多數用途,偽隨機已經足夠好。
事實證明,Python 的random模組使用一個名為梅森旋轉器的良好 PRNG。當你請求一個隨機數時,旋轉器會生成其序列中的下一個數字。如果你請求足夠多[1]個數字,它們最終會重複。
敏銳的讀者可能會發現這個計劃中的一個缺陷。它如何確定要開始生成的第一個數字?事實證明,Python 使用時間、機器名稱、昨天的棒球比分、好萊塢票房收入和其他不太可能重複的神秘事物[2]的組合來播種生成器。
讓我們探索一下random模組。在此過程中,我們將學習range、for 迴圈和種子。
import random
help(random)
dir(random)
# range creates a list of ints.
help(range)
print range(0,10)
print range(10)
r = range(5,50,5)
print r
for ii in range(10):
print ii
# i,j, ii, jj, and the like are conventional variable
# names for counters, derived from mathematics
# we favor ii, since it's totally clear then that
# var has no inherent meaning
for ii in range(100):
# note that we don't use ii in the loop,
# we just want 100 of them!
print random.random()
# if we set the seed, we guarantee that we will
# get the same answer
random.seed(18485)
random.random() # should give 0.67979361840812036