尝试制作二维随机游走函数,为什么会出现 "unsupported operand type(s) for +: 'float' and 'NoneType'" 错误?

Trying to make a 2-D random walk function, why am I getting "unsupported operand type(s) for +: 'float' and 'NoneType'" error?

这里我做了一个二维随机游走,其中“角色”只能直线向上、向下、向左或向右移动:

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

我的输出效果很好,我得到了随机游走的数组。 现在我在这里尝试相同的地方,这次我希望我的随机行走角色沿着角度 theta 的方向前进,因此 [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

这段代码似乎失败了,我遇到了问题:

[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'

所以我已经按照与以前相同的方式定义了数组,并且我的新函数 (dirs(r)) returns 是一个数组,所以出现此错误的原因可能是什么?谢谢!

你的函数:

def dirs(x):
    print(np.array( [math.cos(x), math.sin(x)] ))

只打印数组,不返回它。这就是为什么 moveNone,并且当您尝试添加 float 类型的 locations[i-1]move 类型时会出现错误17=]。将其更改为:

def dirs(x):
    return np.array( [math.cos(x), math.sin(x)] )