Python實現隨機漫步

隨機漫步生成是無規則的,是系統自行選擇的結果。根據設定的規則自定生成,上下左右的方位,每次所通過的方向路徑。app

首先,建立一個RandomWalk()類和fill_walk()函數dom

random_walk.py函數

from random import choice

class Randomwalk ():
    '''一個生成隨機數漫步的類'''

    def __init__(self,num_point=5000):
        '''初始化隨機漫步的屬性'''
        self.num_point = num_point

        #全部隨機漫步的開始都是座標[0,0]
        self.x_lab = [0]
        self.y_lab = [0]

    def fill_walk(self):
        '''計算隨機漫步的全部點'''

        while len(self.x_lab) < self.num_point:
            #決定前進方向以及前進的距離
            x_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance

            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance

            #拒絕原地不動
            if x_step == 0 and y_step == 0:
                continue

            #計算下一個點X和Y的值
            next_x = self.x_lab[-1] + x_step
            next_y = self.y_lab[-1] + y_step

            self.x_lab.append(next_x)
            self.y_lab.append(next_y)

二、繪製隨機漫步圖spa

rw_visual.py

import matplotlib.pyplot as plt
from random_walk import Randomwalk
from random import choice


rw = Randomwalk()
rw.fill_walk()
plt.scatter(rw.x_lab,rw.y_lab,s=15)
plt.show()

三、生成效果圖片code

 

四、修改代碼-->隱藏邊框
rw_visual.py

import matplotlib.pyplot as plt
from random_walk import Randomwalk
from random import choice


while True:
    rw = Randomwalk()
    rw.fill_walk()

    #設置繪畫窗口大小
    plt.figure(dpi=128,figsize=(10,6))

    point_numbers = list(range(rw.num_point))
    #突出起點(0,0)和終點
    plt.scatter(0,0,c='green',edgecolors='none',s=100)
    plt.scatter(rw.x_lab[-1],rw.y_lab[-1],c='red',edgecolors='none',s=100)

    #隱藏座標軸
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.scatter(rw.x_lab,rw.y_lab,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
    plt.show()

    keep_running = input("Make another walk?(y/n): ")
    keep_running = keep_running.lower()
    if keep_running == 'n':
        break

五、展現效果blog

相關文章
相關標籤/搜索