時間:2021-03-29來源:www.www.newsthatmovesu.com作者:電腦系統城
注:需要python的內置函數random,不需安裝,直接導入即可
import random
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
- * - 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#打印每一次的累積步數 |
運行如下:
需要用到numpy庫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#-*- 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實現隨機游走的詳細解釋的文章就介紹到這了
2022-03-01
PHP如何從txt文件中讀取數據詳解2022-03-01
分享5個方便好用的Python自動化腳本2021-03-29
Python中pycharm編輯器界面風格修改方法