【问题标题】:Python: TypeError: only length-1 arrays can be converted to Python scalarsPython:TypeError:只有长度为 1 的数组可以转换为 Python 标量
【发布时间】:2017-08-20 19:17:55
【问题描述】:

我有一个功能

f(x) = sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

我需要求解线性方程组

w0 + w1x1 + w2(x1)**2 + ... + wn(x1)**n = f(x1)

我解决了这个问题,但我在绘制它时遇到了问题

from math import sin, exp
from scipy import linalg
import numpy as np

b = []
def f(x):
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

for i in [1, 15]:
    b.append(f(i))

A = []

for i in [1, 15]:
    ij = []
    x0 = i ** 0
    x1 = i ** 1
    ij.append(x0)
    ij.append(x1)
    A.append(ij)

matrix = np.array(A)
b = np.array(b).T

x = linalg.solve(matrix, b)
from matplotlib import pyplot as plt
plt.plot(x, f(x))

但它会返回

TypeError: only length-1 arrays can be converted to Python scalars

我该如何解决这个问题?

【问题讨论】:

    标签: python matplotlib scipy


    【解决方案1】:

    math.sinmath.exp 需要标量输入。如果你传递一个数组,你会得到一个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 数组:

    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)
    

    【讨论】:

    • 为什么会这样?
    • 标准库中math 模块中的函数需要标量作为输入。等效的 NumPy 函数旨在与 NumPy 数组一起使用。 x 是一个 NumPy 数组,所以你需要使用np.sin(x),而不是math.sin(x)
    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 2013-03-15
    • 1970-01-01
    • 2021-12-05
    • 2016-03-10
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多