I am attempting to make a plot using Chebyshev nodes and Lagrange polynomials shown in the following but I am receiving the error x, y, and format string must not be None. Why is this happening, how can I fix it/ plot what I want to appropriately?
EDIT: I have updated my code to fix the original error x, y, and format string must not be None and now I have the error unsupported operand type(s) for -: 'list' and '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))
CodePudding user response:
You can solve this by using 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))
This will return array([-5.08984891, 1.04582888, 6.70431625])