From 791da0ad9cef70aed11b612af23e4339f888e998 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Fri, 26 Oct 2012 14:00:25 -0400 Subject: [PATCH] Update the lagrange_polynomial() function to take a list of y-values instead of a function. --- mjo/interpolation.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/mjo/interpolation.py b/mjo/interpolation.py index 4cb5874..0cafc28 100644 --- a/mjo/interpolation.py +++ b/mjo/interpolation.py @@ -38,27 +38,28 @@ def lagrange_coefficient(k, x, xs): -def lagrange_polynomial(f, x, xs): +def lagrange_polynomial(x, xs, ys): """ Return the Lagrange form of the interpolation polynomial in `x` of - `f` at the points `xs`. + at the points (xs[k], ys[k]). INPUT: - - ``f`` - The function to interpolate. - - ``x`` - The independent variable of the resulting polynomial. - ``xs`` - The list of points at which we interpolate `f`. + - ``ys`` - The function values at `xs`. + OUTPUT: - A symbolic function (polynomial) interpolating `f` at `xs`. + A symbolic function (polynomial) interpolating each (xs[k], ys[k]). TESTS:: sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ] - sage: L = lagrange_polynomial(sin, x, xs) + sage: ys = map(sin, xs) + sage: L = lagrange_polynomial(x, xs, ys) sage: expected = 27/16*(pi - 6*x)*(pi - 2*x)*(pi + 2*x)*x/pi^4 sage: expected -= 1/8*(pi - 6*x)*(pi - 2*x)*(pi + 6*x)*x/pi^4 sage: expected -= 1/8*(pi - 6*x)*(pi + 2*x)*(pi + 6*x)*x/pi^4 @@ -67,7 +68,6 @@ def lagrange_polynomial(f, x, xs): True """ - ys = [ f(xs[k]) for k in range(0, len(xs)) ] ls = [ lagrange_coefficient(k, x, xs) for k in range(0, len(xs)) ] sigma = sum([ ys[k] * ls[k] for k in range(0, len(xs)) ]) return sigma @@ -145,7 +145,8 @@ def newton_polynomial(f, x, xs): TESTS: sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ] - sage: L = lagrange_polynomial(sin, x, xs) + sage: ys = map(sin, xs) + sage: L = lagrange_polynomial(x, xs, ys) sage: N = newton_polynomial(sin, x, xs) sage: bool(N == L) True -- 2.44.2