试图创建一个二维随机游走函数,为什么我会收到“不支持的操作数类型+:'float'和'NoneType'”错误?

问题描述

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

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,1],-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,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)) 返回了一个数组,那么我收到此错误的原因可能是什么?谢谢!

解决方法

您的职能:

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

只打印数组,不返回它。这就是为什么 moveNone,当您尝试添加 locations[i-1](类型为 float)和 move(类型为 {{)时会出错1}}。改为:

NoneType