Here I made a 2-D random-walk where the "character" can only move straight up, down, left or right:
import random
import numpy as np
import matplotlib.pyplot as plt
# I define the possible moves at each step of the 2D walk
dirs = np.array( [ [1,0], [-1,0], [0,1], [0,-1] ]
# I define the number of steps to take
numSteps = 50
# I set up a 2D array to store the locations visited
locations = np.zeros( (numSteps, 2) ) # numSteps rows, 2 columns
# take steps
for i in range(1, numSteps):
r = random.randrange(4) # random integer from {0,1,2,3}
move = dirs[r] # direction to move
locations[i] = locations[i-1] + move # store the next location
locations
My output works well and I get arrays of the random walk. Now here I'm trying the same where this time I want my random walk character to go in a direction with the angle theta, hence [cos(theta), sin(theta)]:
import random
import numpy as np
import matplotlib.pyplot as plt
import math
import decimal
# I again define the possible moves at each step of the 2D walk, I make it function this time.
# The function works and returns an array (I tested)
def dirs(x):
print(np.array( [math.cos(x), math.sin(x)] ))
# I define the number of steps to take
numSteps = 50
# I set up a 2D array to store the locations visited
locations = np.zeros( (numSteps, 2) ) # numSteps rows, 2 columns
# take steps
for i in range(1, numSteps):
r = random.randrange(314159)/100000 # random integer from {0 to an approximation of pi}
move = dirs(r) # direction to move
locations[i] = locations[i-1] + move # This is where the issue is! Why is this array not considered valid?
locations
Here this code seems to fail, I'm getting the issue:
[0.8116997 0.584075 ]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-c81f4b47e64d> in <module>()
14 r = random.randrange(314159)/100000 # random integer from {0 to an approximation of pi}
15 move = dirs(r) # direction to move
---> 16 locations[i] = locations[i-1] + move # This is where the issue is! Why is this array not considered valid?
17
18 locations
TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'
So I have defined the array in the same way as before, and my new function (dirs(r)) returns an array, so what could be the reason I am getting this error? Thank you!
Your function:
def dirs(x):
print(np.array( [math.cos(x), math.sin(x)] ))
is only printing the array, not returning it. That is why move
is None
, and you get an error when you try to add locations[i-1]
, of type float
, and move
, of type NoneType
. Change it to:
def dirs(x):
return np.array( [math.cos(x), math.sin(x)] )