我想使用 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()