python實現(xiàn)隨機漫步算法
本文實例為大家分享了python實現(xiàn)隨機漫步的具體代碼,供大家參考,具體內(nèi)容如下
編寫randomwalk類
from random import choice
class randomwalk():
def __init__(self,num_points=5000):
self.num_points=num_points
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):
while len(self.x_values)<self.num_points:
x_direction=choice([1,-1])
x_distance=choice([0,1,2,3,4,5])
x_step=x_direction*x_distance
y_direction=choice([1,-1])
y_distance=choice([0,1,2,3,4,5])
y_step=y_direction*y_distance
if x_step==0 and y_step==0:
continue
self.x_values.append(self.x_values[-1]+x_step)
self.y_values.append(self.y_values[-1]+y_step)
choice([1,-1])*步數(shù)巧妙的完成了隨機方向,x軸隨機加y軸隨機使得4個方向的隨機漫步得以完成
顯示隨機漫步點
import matplotlib.pyplot as plt
from random_walk import randomwalk
while True:
rw=randomwalk()
rw.fill_walk()
plt.figure(figsize=(15,8))
point_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,s=1,c=point_numbers,
edgecolor='none',cmap=plt.cm.Blues)
plt.scatter(rw.x_values[0],rw.y_values[0],s=50,edgecolor='none',
c='green')
plt.scatter(rw.x_values[-1],rw.y_values[-1],s=50,edgecolor='none',
c='green')
plt.show()
a=input("do you want to walk again?(y/n)")
if a=='n':
break
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python常駐任務(wù)實現(xiàn)接收外界參數(shù)代碼解析
這篇文章主要介紹了Python常駐任務(wù)實現(xiàn)接收外界參數(shù)代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
selenium 安裝與chromedriver安裝的方法步驟
這篇文章主要介紹了selenium 安裝與chromedriver安裝的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06
python怎樣判斷一個數(shù)值(字符串)為整數(shù)
這篇文章主要介紹了python怎樣判斷一個數(shù)值(字符串)為整數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
windows10在visual studio2019下配置使用openCV4.3.0
這篇文章主要介紹了windows10在visual studio2019下配置使用openCV4.3.0,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
pytorch載入預(yù)訓(xùn)練模型后,實現(xiàn)訓(xùn)練指定層
今天小編就為大家分享一篇pytorch載入預(yù)訓(xùn)練模型后,實現(xiàn)訓(xùn)練指定層,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

