Python&数学基礎

ランダムウォーク


プログラム(Python 3.10.4)


    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import numpy as np
    import pandas as pd


    def randomwalk():
        x = []
        y = []
        num = 50
        p = 0.6
        val = 0
        fig, ax = plt.subplots(figsize=(6, 4))
        ax.set_xlim(0, num)
        ax.set_ylim(-1*num/2, num/2)
        x = [i+1 for i in range(num)]
        for k in range(num):
            a = 1
            if np.random.rand() > p:
                a = -1
            val += a
            y.append(val)
        plt.scatter(x, y, c='k', s=20, marker='.')
        plt.title('RandomWalk'+' N='+str(num))
        plt.show()