Simulating a 2D Random Walk in Python

  • Share this:

Code introduction


This function simulates a random walk on a 2D plane, recording the coordinate changes at each step.


Technology Stack : Numpy, random walk simulation

Code Type : The type of code

Code Difficulty :


                
                    
import numpy as np

def random_walk(n_steps):
    """
    Simulates a random walk on a 2D plane using numpy.
    """
    x, y = 0, 0
    walk = np.zeros((n_steps, 2))
    
    for i in range(n_steps):
        step = np.random.choice([1, -1, 0, 0], p=[0.2, 0.2, 0.6])
        if np.random.choice([0, 1], p=[0.5, 0.5]):
            step = np.random.choice([1, -1, 0, 0], p=[0.2, 0.2, 0.6])
        
        if step == 1:
            x += 1
        elif step == -1:
            x -= 1
        
        if np.random.choice([0, 1], p=[0.5, 0.5]):
            step = np.random.choice([1, -1, 0, 0], p=[0.2, 0.2, 0.6])
        
        if step == 1:
            y += 1
        elif step == -1:
            y -= 1
        
        walk[i] = [x, y]
    
    return walk

# JSON Explanation