使用numpy.sqrt
而不是math.sqrt
。numpy.sqrt
期望标量或数组作为输入,另一方面math.sqrt
只能处理标量。
>>> import numpy as np
>>> import math
>>> a = np.arange(5)
>>> np.sqrt(a)
array([ 0. , 1. , 1.41421356, 1.73205081, 2. ])
#error
>>> math.sqrt(a)
Traceback (most recent call last):
File "<ipython-input-78-c7d50051514f>", line 1, in <module>
math.sqrt(a)
TypeError: only length-1 arrays can be converted to Python scalars
>>>