操作数无法与形状 (100,) (7,) 一起广播

问题描述 投票:0回答:1

我想使用 matplotlib 绘制 f(x) 和 Ln(x) 函数,但收到此错误:

ValueError: operands could not be broadcast together with shapes (100,) (7,)

我的代码:

import numpy as np
from matplotlib import pyplot as plt

a = [1, 2.5, 3, 4, 5, 6, 7.8, 8, 9]

def f(x):
    return np.cos(x/3)*np.sin(x/2)

xi = np.array([a[i]+(a[i+1]-a[i])/4 for i in range(len(a)-1)])
yi = np.array([f(xj) for xj in xi])

def Ln(x):
    Ln = 0
    for xj, yj in zip(xi, yi):
        Ln += yj*np.prod((x-xi[xi != xj])/(xj-xi[xi != xj]))
    return Ln

x = np.linspace(-10, 10, 100)
plt.plot(x, Ln(x), 'gold')
plt.plot(x, f(x), 'purple')
plt.show()
python numpy matplotlib valueerror
1个回答
0
投票
    您得到的
  • error
    是因为
    x
    xi
    的长度,并且您正在使用
    np.pod()
  • 更新
    Ln()
    功能
def Ln(x):
    Ln = np.zeros_like(x)
    for xj, yj in zip(xi, yi):
        p = 1
        for xi_val in xi[xi != xj]:
            p *= (x - xi_val) / (xj - xi_val)
        Ln += yj * p
    return Ln

© www.soinside.com 2019 - 2024. All rights reserved.