I want to interpolate a polynomial with the Lagrange method, but this code doesn't work:
def interpolate(x_values, y_values):
def _basis(j):
p = [(x - x_values[m])/(x_values[j] - x_values[m]) for m in xrange(k + 1) if m != j]
return reduce(operator.mul, p)
assert len(x_values) != 0 and (len(x_values) == len(y_values)), 'x and y cannot be empty and must have the same length'
k = len(x_values)
return sum(_basis(j) for j in xrange(k))
I followed Wikipedia, but when I run it I receive an IndexError at line 3!
Thanks
interpolate([1, 2, 3], [1, 4, 9])
it returns-0.5x^2 + 1.5x
? Take a look at this: i.imgur.com/MkATz.gif – Upspring