前言
使用包包括,numpy, pandas, matplotlib
产生随机数
np.random.seed()
可以用来设定一个种子,使后续产生相同的随机数。
np.random.rand()
在默认下会产生一个0-1之间的浮点类型的数字。
np.random.randint(x, y)
在x到y-1 中产生一个随机整数。
小游戏
基于上述知识,我们可以写一个丢骰子移动的小游戏。
# 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次的结果。
这里有个小问题,由于一共十次结果,每次结果包含100步的得分数字信息,但进行绘图时,需要将这个10X100
的表格转变为100X10
,利用np.transpose
将表格调换。
# 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()
还可以增加一个随机数的判断,比如有1%的概率骰子掉了。(hhh
if np.random.rand() <= 0.001 :
step = 0
最后可以再看一看结果的分布情况。
# 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()
网友评论