In [1]:
# input given points
points = [
(0, 2),
(1, 2),
(2, 1),
(3, -1),
]
#
In [2]:
n = len(points)
X = [p[0] for p in points]
Y = [p[1] for p in points]
In [3]:
L = []
var('x')
for k in range(n):
Lnk = (prod([(x - X[i]) for i in range(len(X)) if i != k])) / (prod([(X[k] - X[i]) for i in range(len(X)) if i != k]))
L.append(Lnk.simplify_full())
In [4]:
for i, l in enumerate(L):
show(LatexExpr(r"L_{{ {}, {} }} = ".format(n, i)), l)
In [5]:
P = sum([Y[k] * L[k] for k in range(n)])
show(P.simplify_full())
In [6]:
# some sanity checking
for k in range(n):
yc = P.subs(x=X[k])
yg = Y[k]
assert yc == yg, "computed y {} != {} given y".format(yc, yg)
In [7]:
R = max(max((p[0], p[1])) for p in points) + 2
scatter_plot(points) + plot(P, xmax=R, ymax=R, ymin=-R, xmin=-R)
Out[7]:
In [ ]: