Random Walk Simulation with Visualization

  • Share this:

Code introduction


This function performs a random walk process and visualizes the result using matplotlib. It randomly selects the direction and number of steps, then records the position of each step and plots it.


Technology Stack : Python, PyTorch (not directly used), random (random module), matplotlib (data visualization library)

Code Type : Data visualization

Code Difficulty : Intermediate


                
                    
def random_walk(num_steps, start_point):
    import random
    import matplotlib.pyplot as plt

    x, y = start_point
    x_positions, y_positions = [x], [y]

    for _ in range(num_steps):
        step = random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
        x += step[0]
        y += step[1]
        x_positions.append(x)
        y_positions.append(y)

    plt.plot(x_positions, y_positions, marker='o')
    plt.title('Random Walk')
    plt.xlabel('X Position')
    plt.ylabel('Y Position')
    plt.show()