Python:TypeError:只能将长度为1的数组转换为Python标量 [英] Python: TypeError: only length-1 arrays can be converted to Python scalars

查看:83
本文介绍了Python:TypeError:只能将长度为1的数组转换为Python标量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

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)

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

I solve that but I have a problem with plot it

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

我该如何解决这个问题?

How can I solve this problem?

推荐答案

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)

这篇关于Python:TypeError:只能将长度为1的数组转换为Python标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆