--- /dev/null
+from sage.all import *
+load('~/.sage/init.sage')
+
+def lagrange_coefficient(k, x, xs):
+ """
+ Returns the coefficient function l_{k}(variable) of y_{k} in the
+ Lagrange polynomial of f. See,
+
+ http://en.wikipedia.org/wiki/Lagrange_polynomial
+
+ for more information.
+
+ INPUT:
+
+ - ``k`` -- the index of the coefficient.
+
+ - ``x`` -- the symbolic variable to use for the first argument
+ of l_{k}.
+
+ - ``xs`` -- The list of points at which the function values are
+ known.
+
+ OUTPUT:
+
+ A symbolic function of one variable.
+
+ TESTS::
+
+ sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ]
+ sage: lagrange_coefficient(0, x, xs)
+ 1/8*(pi - 6*x)*(pi - 2*x)*(pi + 6*x)*x/pi^4
+
+ """
+ numerator = product([x - xs[j] for j in range(0, len(xs)) if j != k])
+ denominator = product([xs[k] - xs[j] for j in range(0, len(xs)) if j != k])
+
+ return (numerator / denominator)
+
+
+
+def lagrange_polynomial(f, x, xs):
+ """
+ Return the Lagrange form of the interpolation polynomial in `x` of
+ `f` at the points `xs`.
+
+ INPUT:
+
+ - ``f`` - The function to interpolate.
+
+ - ``x`` - The independent variable of the resulting polynomial.
+
+ - ``xs`` - The list of points at which we interpolate `f`.
+
+ OUTPUT:
+
+ A symbolic function (polynomial) interpolating `f` at `xs`.
+
+ TESTS::
+
+ sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ]
+ sage: L = lagrange_polynomial(sin, x, xs)
+ 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
+ sage: expected += 27/16*(pi - 2*x)*(pi + 2*x)*(pi + 6*x)*x/pi^4
+ sage: bool(L == expected)
+ 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
"""
from sage.all import *
+from functools import reduce
def legend_latex(obj):
"""
legend label.
"""
return '$%s$' % latex(obj)
+
+def product(factors):
+ """
+ Returns the product of the elements in the list `factors`. If the
+ list is empty, we return 1.
+
+ TESTS:
+
+ Normal integer multiplication::
+
+ sage: product([1,2,3])
+ 6
+
+ And with symbolic variables::
+
+ sage: x,y,z = var('x,y,z')
+ sage: product([x,y,z])
+ x*y*z
+
+ """
+ return reduce(operator.mul, factors, 1)