Here is the code for a random walk I made which I attempted to constrain where -5 < y < 5:
import random
import numpy as np
import matplotlib.pyplot as plt
import math
import decimal
def dirs(x):
return np.array( [math.cos(x), math.sin(x)] )
def constrainedRandomWalk(x):
numSteps = x
locations = np.zeros( (numSteps, 2) )
for i in range(1, numSteps):
r = random.randrange(628318)/100000
move = dirs(r)
locations[i] = locations[i-1] + move
if -5<locations[i][1]<5:
continue
#return locations
plt.figure(figsize=(8,8))
plt.plot( locations[:,0], locations[:,1], alpha=0.7 );
plt.xlim([-20,20])
plt.ylim([-20,20])
I attempted to constrain the "walking character" by setting a condition on the loop that
if -5<locations[i][1]<5:
continue
However, as you can see here, the character leaves the -5<y<5 region:
Can anyone let me know how to actually constrain the random walk and why this method doesn't work? Thank you!