-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import random
position=0#设置初始位置
walk=[]#保存位置
steps=500#设置步数为500步
for i in range(steps):
step=1 if random.randint(0,1) else -1#如果随机值等于0则step为1,反之为0
position+=step#改变位置(正,负)
walk.append(position)
fig=plt.figure()#生成窗口
ax=fig.add_subplot(211)#返回一个axes对象,里面的参数abc表示在一个figure窗口中,有a行b列个小窗口,然后本次plot在第c个窗口中
ax.plot(walk)
ax=fig.add_subplot(223)
ax.plot(walk)
ax=fig.add_subplot(224)
ax.plot(walk)
plt.show()
#print walk#打印每一次的累积步数
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
nwalks = 8
nsteps = 500
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()
到此这篇关于Python实现随机游走的详细解释的文章就介绍到这了,更多相关Python 随机游走内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!