随机漫步:从0开始,步进为1或-1(向前走或向后走),且两种步进的概率相等。下面我们用python内置的random库和大名鼎鼎的numpy库分别实现1000步的随机漫步模拟。
random库实现随机漫步
import random
import matplotlib.pyplot as plt
steps = 1000
position = 0
walk = [position]
for i in range(steps):
step = 1 if random.randint(0,1) else -1
position += step
walk.append(position)
plt.plot(walk)
plt.show()
运行后结果如下所示:
numpy库实现随机模拟
import numpy as np
import matplotlib.pyplot as plt
steps = 1000
draws = np.random.randint(0, 2, steps)
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()
plt.plot(walk)
plt.show()
运行后结果如下:
|