用random和numpy和matplotlib作出图象

img

用random,numpy,matplotlib函数写程序,作图

img

img

img

img

img


# 随机漫步demo
from random import choice

import numpy as np
from matplotlib import pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

class RandomWalk():
    """一个生成随机漫步数据的类"""
    num_points = 0
    x_values = []
    y_values = []
    dis_values = []

    def __init__(self, num_points=500):
        self.num_points = num_points
        # 所有随机漫步都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]
        self.dis_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            # 决定前进方向
            x_direction = choice([1, -1])
            x_distance = 1
            x_step = x_direction * x_distance

            # 计算下一个点的x和y
            next_x = self.x_values[-1] + x_step
            next_y = 0

            self.x_values.append(next_x)
            self.y_values.append(next_y)
            if (len(self.x_values) > 0):
                self.dis_values.append(next_x - 0)
            else:
                self.dis_values.append(x_step)

x = np.arange(10000)
for i in np.arange(5):
    rw = RandomWalk(num_points=10000)
    rw.fill_walk()
    plt.scatter(x, rw.dis_values, s=5,marker='*')
    plt.title("第"+str(i+1)+"次运行结果")
    plt.show()