标签:
在python中,可以利用数组操作来模拟随机游走。
下面是一个单一的200步随机游走的例子,从0开始,步长为1和-1,且以相等的概率出现。纯Python方式实现,使用了内建的 random 模块:
# 随机游走 import matplotlib.pyplot as plt import random position = 0 walk = [position] steps = 200 for i in range(steps): step = 1 if random.randint(0, 1) else -1 position += step walk.append(position) fig = plt.figure()
ax = fig.add_subplot(111) ax.plot(walk) plt.show()
第二种方式:简单的把随机步长累积起来并且可以可以使用一个数组表达式来计算。因此,我用 np.random 模块去200次硬币翻转,设置它们为1和-1,并计算累计和:
# 随机游走 import matplotlib.pyplot as plt import numpy as np nsteps = 200 draws = np.random.randint(0, 2, size=nsteps) steps = np.where(draws > 0, 1, -1) walk = steps.cumsum() fig = plt.figure() ax = fig.add_subplot(111) ax.plot(walk) plt.show()
# 随机游走 import matplotlib.pyplot as plt import numpy as np nwalks = 5 nsteps = 200 draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1 steps = np.where(draws > 0, 1, -1) walks = steps.cumsum(1) fig = plt.figure() ax = fig.add_subplot(111) for i in range(nwalks): ax.plot(walks[i]) plt.show()
标签:
原文地址:http://www.cnblogs.com/hhh5460/p/4356635.html