Skip to content

Instantly share code, notes, and snippets.

@anyuzx
Last active September 23, 2019 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anyuzx/ea4b6c8e831ff923640aeda185241d14 to your computer and use it in GitHub Desktop.
Save anyuzx/ea4b6c8e831ff923640aeda185241d14 to your computer and use it in GitHub Desktop.
Generate 2D random walk trajectory
import numpy as np
def walk(n):
# check if the number of steps is an integer
if int(n) != n:
print('number of steps should be an integer')
return None
# the initial position is (0,0)
xy_0 = np.array([0.0, 0.0])
# generate displacements of each step
dxdy = np.random.randn(int(n), 2)
# cumulative sum displacement to get positions at each step
xy = xy_0 + np.cumsum(dxdy, axis=0)
# insert the initial position at the head of the array
xy = np.vstack((xy_0, xy))
# since javascript has no 2D array, it is better to
# return the x-position and y-position, separately
return xy[:,0], xy[:,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment