7.2k views
1 vote
Write a function randomWalk(...) which simulates one path (or trajectory) of a simple symmetric random walk with 2N time steps (i.e. from 0,1,2,...,2N) starting at ????0=0 .

Input: lengthOfRandomWalk = 2N

Output: samplePath: Array of length 2N+1 with the entire path of the random walk on 0,1,2,...,2N

1 Answer

2 votes

Answer:

import numpy as np

import random

import matplotlib.pyplot as plt

def randomWalk(L):

# S is a 2d array where x = row1= S[0][:], y = row2 = S[1][:]

S = np.zeros(shape=(2,L+1))

directions = [1,2,3,4]

for i in range(1, L+1):

direction = np.random.choice(directions)

if direction == 1:

S[0][i] = S[0][i-1] + 1; S[1][i] = S[1][i-1] # go right

elif direction == 2:

S[0][i] = S[0][i-1] - 1; S[1][i] = S[1][i-1] # go left

elif direction == 3:

S[0][i] = S[0][i-1]; S[1][i] = S[1][i-1] + 1 # go up

else:

S[0][i] = S[0][i-1]; S[1][i] = S[1][i-1] - 1; # go down

samplePath = S

return samplePath

n = 100;

path = randomWalk(2*n)

print(path)

x = path[0][:]; y = path[1][:];

plt.figure(1)

plt.plot(x,y,'-')

plt.ylabel('y')

plt.xlabel('x')

plt.show()

Step-by-step explanation:

User DLunin
by
5.2k points