python--随机漫步数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_38950569/article/details/97972849

创建随机类

from random import  choice
import  matplotlib.pyplot as plt

'''创建随机漫步类'''
class RandomWalk():
    def __init__(self,num_point = 5000):
        '''初始化随机漫步的属性'''
        self.num_point = num_point

        self.x_valuer = [0]
        self.y_valuer = [0]

选择方向

 def fill_walk(self):
        '''计算随机漫步包含的所有点'''
        #不断漫步,直到达到指定的长度
        while len(self.x_valuer) < self.num_point:
            # 决定前进的方向以及盐这个方向前进的距离
            x_direction = choice([1, -1]) #方向(要么向右+1,要么向左-1)
            x_distance = choice([0, 1,  2, 3, 4]) #距离(随机选1~4)(通过包含0,表示不但可以走x,还能走y)
            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_valuer[-1] + x_step #最后一个值相加
            next_y = self.y_valuer[-1] + y_step

            self.x_valuer.append(next_x)
            self.y_valuer.append(next_y)

显示漫步图

这里具体为什么这么写请看上一章节

while True:
    rw = RandomWalk()
    rw.fill_walk()
    plt.scatter(rw.x_valuer, rw.y_valuer, s=15)
    plt.show()
    keep_running = input("是否退出?(Y/n):")
    if keep_running == 'y':
        break

对漫步图进行重新规划

#显示漫步图
#模拟多次随机漫步
#给点着色
#重绘起始点
#隐藏坐标轴
#增加点数
#设置窗口分辨率及尺寸

while True:
    rw = RandomWalk(60000)
  #  rw = RandomWalk()
    rw.fill_walk()
    #设置窗口分辨率及尺寸
    plt.figure(dpi=128, figsize=(12, 8))
    point_numbers = list(range(rw.num_point))
    #给点上色
   # plt.scatter(rw.x_valuer, rw.y_valuer, c= point_numbers, cmap = plt.cm.Blues, edgecolors= 'none', s=15)
   
   plt.scatter(rw.x_valuer, rw.y_valuer, c= point_numbers, cmap = plt.cm.Blues, edgecolors= 'none', s=1)
   #突出终点和起点
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_valuer[-1], rw.y_valuer[-1], c='red',edgecolors='none',s=100)
   #隐藏x,y坐标
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)
    plt.show()
    keep_running = input("是否退出?(Y/n):")
    if keep_running == 'y':
        break

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38950569/article/details/97972849