math 中的函数通常需要一个数字作为参数;而numpy 中的函数通常期望从单个数字到多维数组的任何内容,并将数学函数应用于数组中的每个元素。
例如:
>>> import math
>>> import numpy as np
>>> math.sqrt(4)
2.0
>>> math.sqrt(25)
5.0
>>> np.sqrt(4)
2.0
>>> np.sqrt(25)
5.0
>>> np.sqrt([4,25])
array([2., 5.])
>>> math.sqrt([4,25])
TypeError: must be real number, not list
>>> math.sqrt(np.array([4,25]))
TypeError: only size-1 arrays can be converted to Python scalars
事实证明,包含单个数字的 numpy 数组能够在需要时将自己隐式转换为不带数组的单个数字,所以这是可行的:
>>> math.sqrt(np.array([[25]]))
5.0
您收到的错误消息是告诉您“数组y 包含多个数字,因此无法将其转换为单个数字,因此您无法在其上调用math.sin。”
如果要将math 中的函数应用于列表中的每个元素,可以使用list comprehension 或builtin function map 来实现。但是请注意,numpy 的全部意义在于在大型数组上非常快速地执行计算,而使用列表推导式或map 将无法实现这一目的。
>>> list(map(math.sqrt, [4, 25]))
[2.0, 5.0]
>>> [math.sqrt(x) for x in [4,25]]
[2.0, 5.0]