Python實(shí)現(xiàn)隨機(jī)游走的詳細(xì)解釋
注:需要python的內(nèi)置函數(shù)random,不需安裝,直接導(dǎo)入即可
import random
-*- coding: utf-8 -*-import matplotlib.pyplot as pltimport randomposition=0#設(shè)置初始位置walk=[]#保存位置steps=500#設(shè)置步數(shù)為500步for i in range(steps): step=1 if random.randint(0,1) else -1#如果隨機(jī)值等于0則step為1,反之為0 position+=step#改變位置(正,負(fù)) 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ù)
運(yùn)行如下:
需要用到numpy庫
#-*- coding: utf-8 -*-import matplotlib.pyplot as pltimport numpy as npnwalks = 8nsteps = 500draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1steps = 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實(shí)現(xiàn)隨機(jī)游走的詳細(xì)解釋的文章就介紹到這了,更多相關(guān)Python 隨機(jī)游走內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. 淺談python出錯時traceback的解讀3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. Python importlib動態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題6. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析10. Nginx+php配置文件及原理解析
