Skip to content

Instantly share code, notes, and snippets.

@abdullahmujahidali
Created April 23, 2020 20:50
Show Gist options
  • Save abdullahmujahidali/868c5efc91fff50ebd045278071ffc8d to your computer and use it in GitHub Desktop.
Save abdullahmujahidali/868c5efc91fff50ebd045278071ffc8d to your computer and use it in GitHub Desktop.
Random Walk Function
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment