I'm trying to simulate a 2-D random walk in python with boundaries (the particle/object will can't cross the boundaries and must return back). However my version is not vectorised and is very slow. How do I implement it without(or minimising) the use of loops.
Here is my approach
def bound_walk():
Origin = [0, 0] #Starting Point
#All Possible directiom
directions = ((-1, 1), (0, 1), (1, 1),
(-1, 0) , (1, 0),
(-1, -1), (0, -1), (1, -1))
#Directions allowed when x-coordinate reaches boundary
refelectionsx = ((-1, 1), (0, 1),
(-1, 0),(-1, -1), (0, -1))
#Directions allowed when y-coordinate reaches boundary
refelectionsy = ((-1, 0) , (1, 0),
(-1, -1), (0, -1), (1, -1))
points = [(0, 0)]
for i in range(20000):
direction = choice(directions)
reflection1 = choice(refelectionsx)
reflection2 = choice(refelectionsy)
if Origin[0]>50: #Boundary==50
Origin[0] += reflection1[0]
elif Origin[0]<-50:
Origin[0] -= reflection1[0]
else:
Origin[0] += direction[0]
if Origin[1]>50:
Origin[1] += reflection2[1]
elif Origin[1] < -50:
Origin[1] -= reflection2[1]
else:
Origin[1] += direction[1]
points.append(Origin[:])
return points