]>
gitweb.michael.orlitzky.com - sage.d.git/blob - mjo/interpolation.py
2 load('~/.sage/init.sage')
4 def lagrange_coefficient(k
, x
, xs
):
6 Returns the coefficient function l_{k}(variable) of y_{k} in the
7 Lagrange polynomial of f. See,
9 http://en.wikipedia.org/wiki/Lagrange_polynomial
15 - ``k`` -- the index of the coefficient.
17 - ``x`` -- the symbolic variable to use for the first argument
20 - ``xs`` -- The list of points at which the function values are
25 A symbolic function of one variable.
29 sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ]
30 sage: lagrange_coefficient(0, x, xs)
31 1/8*(pi - 6*x)*(pi - 2*x)*(pi + 6*x)*x/pi^4
34 numerator
= product([x
- xs
[j
] for j
in range(0, len(xs
)) if j
!= k
])
35 denominator
= product([xs
[k
] - xs
[j
] for j
in range(0, len(xs
)) if j
!= k
])
37 return (numerator
/ denominator
)
41 def lagrange_polynomial(f
, x
, xs
):
43 Return the Lagrange form of the interpolation polynomial in `x` of
44 `f` at the points `xs`.
48 - ``f`` - The function to interpolate.
50 - ``x`` - The independent variable of the resulting polynomial.
52 - ``xs`` - The list of points at which we interpolate `f`.
56 A symbolic function (polynomial) interpolating `f` at `xs`.
60 sage: xs = [ -pi/2, -pi/6, 0, pi/6, pi/2 ]
61 sage: L = lagrange_polynomial(sin, x, xs)
62 sage: expected = 27/16*(pi - 6*x)*(pi - 2*x)*(pi + 2*x)*x/pi^4
63 sage: expected -= 1/8*(pi - 6*x)*(pi - 2*x)*(pi + 6*x)*x/pi^4
64 sage: expected -= 1/8*(pi - 6*x)*(pi + 2*x)*(pi + 6*x)*x/pi^4
65 sage: expected += 27/16*(pi - 2*x)*(pi + 2*x)*(pi + 6*x)*x/pi^4
66 sage: bool(L == expected)
70 ys
= [ f(xs
[k
]) for k
in range(0, len(xs
)) ]
71 ls
= [ lagrange_coefficient(k
, x
, xs
) for k
in range(0, len(xs
)) ]
72 sigma
= sum([ ys
[k
] * ls
[k
] for k
in range(0, len(xs
)) ])