-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import random
position=0#設(shè)置初始位置
walk=[]#保存位置
steps=500#設(shè)置步數(shù)為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對象,里面的參數(shù)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#打印每一次的累積步數(shù)
#-*- 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)#累積步數(shù)
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(nwalks):
ax.plot(walks[i])
plt.show()
到此這篇關(guān)于Python實現(xiàn)隨機游走的詳細解釋的文章就介紹到這了,更多相關(guān)Python 隨機游走內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!