我试图使用以下所示的切比雪夫节点和拉格朗日多项式进行绘图,但我收到错误x, y和格式字符串不得为None。为什么会发生这种情况,我如何修复它/情节我想适当?
编辑:我已经更新了我的代码来修复原始错误x, y和格式字符串不得为None,现在我有错误不支持的操作数类型(s) -: 'list'和'int'
import numpy as np
def lagrange(x, z, f):
d = len(x)
if len(x) != len(z):
print("Error: the length of x and z is different")
else:
p = 0
for i in range (d):
L = 1
for j in range (d):
if j != i:
L *= (z-x[j])/(x[i] - x[j])
p += f[i]*L
return p
def f(x):
return np.cos(x)
d = [0.1, 4, 0.2]
g = [-0.3, 0, 0.3]
lagrange(d, g, f(d))
你可以使用np.array:
来解决这个问题import numpy as np
def lagrange(x, z, f):
d = len(x)
if len(x) != len(z):
print("Error: the length of x and z is different")
else:
p = 0
for i in range (d):
L = 1
for j in range (d):
if j != i:
L *= (z-x[j])/(x[i] - x[j])
p += f[i]*L
return p
def f(x):
return np.cos(x)
d = np.array([0.1, 4, 0.2])
g = np.array([-0.3, 0, 0.3])
lagrange(d, g, f(d))
这将返回array([-5.08984891, 1.04582888, 6.70431625])