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)#返回一個(gè)axes對(duì)象,里面的參數(shù)abc表示在一個(gè)figure窗口中,有a行b列個(gè)小窗口,然后本次plot在第c個(gè)窗口中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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析2. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML3. python excel和yaml文件的讀取封裝4. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)5. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問題及解決6. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊7. Docker鏡像管理常用操作代碼示例8. 關(guān)于 Android WebView 的內(nèi)存泄露問題9. 詳解docker pull 下來的鏡像都存到了哪里10. Python中內(nèi)建模塊collections如何使用
