且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:TypeError:只能将长度为1的数组转换为Python标量

更新时间:2022-03-21 18:41:36

math.sinmath.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, expmath 模块加载 sinexp 并将它们定义为函数在全局命名空间中.所以 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 的 sinexp 函数.

import numpy as np
def f(x):
    return np.sin(x/5.0)*np.exp(x/10.0) + 5*np.exp(-x/2.0)