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)#每一次的步長(zhǎng)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. 不同瀏覽器對(duì)XML的解析是不同的2. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向3. 告別AJAX實(shí)現(xiàn)無刷新提交表單4. 讀寫xml文件的2個(gè)小函數(shù)5. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理6. XML入門的常見問題(一)7. asp讀取xml文件和記數(shù)8. asp使用Weekday函數(shù)計(jì)算項(xiàng)目的結(jié)束時(shí)間9. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案10. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案
