RandomWalk随机游走

RandomWalk随机游走:

在自然界,物理学,生物学,化学,经济学等众多领域,随机游走都有实际的用途,例如,其可以描述一个漂浮在水滴上的花粒因受到水分子的作用力而在水滴表面随机移动。诸如此类的不规律无规则的自然现象及活动,因此具有一定的研究意义。

代码实现

本次主要使用choice和matplotlib.pyplot

import matplotlib.pyplot as plt
from random import choice


class RandomWalk:
    """定义随机游走属性"""
    def __init__(self, points_num=10000):
        self.points_num = points_num

        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.points_num:

            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_value = x_direction * x_distance

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

            x = self.x_values[-1] + x_value
            y = self.y_values[-1] + y_value

            self.x_values.append(x)
            self.y_values.append(y)


if __name__ == '__main__':
    rw = RandomWalk()
    rw.fill_walk()

    plt.style.use("classic")
    fig, ax = plt.subplots(figsize=(15, 9))                              # 适应屏幕,调整绘图尺寸
    ax.scatter(rw.x_values, rw.y_values, s=15)
    points_numer = range(rw.points_num)
    ax.scatter(rw.x_values, rw.y_values, c=points_numer, 
               cmap=plt.cm.Blues, edgecolors='none', s=15)                # 使用渐近色来表示
    ax.scatter(0, 0, c="green", edgecolors='none', s=100)                 # 将起点突出显示出来
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)       # 将终点突出显示出来
    ax.get_xaxis().set_visible(False)                                     # 隐藏x坐标轴
    ax.get_yaxis().set_visible(False)                                     # 隐藏y坐标轴
    plt.show()

生成的随机游走图:

多展示几张来展示每次生成的点都是随机,无规则无规律的。

posted @ 2025-04-22 15:09  aspxiy  阅读(72)  评论(0)    收藏  举报