前言
使用包包括股囊,numpy, pandas, matplotlib
產(chǎn)生隨機數(shù)
np.random.seed()
可以用來設(shè)定一個種子袜匿,使后續(xù)產(chǎn)生相同的隨機數(shù)。
np.random.rand()
在默認下會產(chǎn)生一個0-1之間的浮點類型的數(shù)字稚疹。
np.random.randint(x, y)
在x到y(tǒng)-1 中產(chǎn)生一個隨機整數(shù)。
小游戲
基于上述知識祭务,我們可以寫一個丟骰子移動的小游戲内狗。
# Numpy is imported, seed is set
# Initialize random_walk
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
# Replace below: use max to make sure step can't go below 0
step = max(0, step -1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
print(random_walk)
還可以加點東西,用matplotlib 把圖畫出來义锥。
# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# Plot random_walk
plt.plot(random_walk)
# Show the plot
plt.show()
一次丟骰子不好玩柳沙,我們還可以看看同時丟10次的結(jié)果。
這里有個小問題拌倍,由于一共十次結(jié)果赂鲤,每次結(jié)果包含100步的得分數(shù)字信息,但進行繪圖時柱恤,需要將這個10X100
的表格轉(zhuǎn)變?yōu)?code>100X10数初,利用np.transpose
將表格調(diào)換。
# numpy and matplotlib imported, seed set.
# initialize and populate all_walks
all_walks = []
for i in range(10) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
all_walks.append(random_walk)
# Convert all_walks to Numpy array: np_aw
np_aw = np.array(all_walks)
# Transpose np_aw: np_aw_t
np_aw_t = np.transpose(np_aw)
# Plot np_aw_t and show
plt.plot(np_aw_t)
plt.show()
還可以增加一個隨機數(shù)的判斷梗顺,比如有1%的概率骰子掉了泡孩。(hhh
if np.random.rand() <= 0.001 :
step = 0
最后可以再看一看結(jié)果的分布情況。
# numpy and matplotlib imported, seed set
# Simulate random walk 500 times
all_walks = []
for i in range(500) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
if np.random.rand() <= 0.001 :
step = 0
random_walk.append(step)
all_walks.append(random_walk)
# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]
# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()