更新时间:2022-03-21 18:41:36
math.sin
和 math.exp
需要标量输入.如果传递数组,则会得到 TypeError
math.sin
and math.exp
expect scalar inputs. If you pass an array, you get a TypeError
In [34]: x
Out[34]: array([ 3.43914511, -0.18692825])
In [35]: math.sin(x)
TypeError: only length-1 arrays can be converted to Python scalars
from math import sin, exp
从 math
模块加载 sin
和 exp
并将它们定义为函数在全局命名空间中.所以 f(x)
在 x
上调用 math
版本的 sin
函数,这是一个 NumPy 数组:
from math import sin, exp
loads sin
and exp
from the math
module and defines them as functions in the global namespace. So f(x)
is calling math
's version of the sin
function on x
which is a NumPy array:
def f(x):
return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)
要修复错误,请改用 NumPy 的 sin
和 exp
函数.
import numpy as np
def f(x):
return np.sin(x/5.0)*np.exp(x/10.0) + 5*np.exp(-x/2.0)