List Manipulation in Mathematica pertaining to Lagrange Interpolation Polynomials in Mathematica

依然范特西╮ 提交于 2019-12-11 06:54:19

问题


I am trying to use a list which is passed to a function in such a way that I can

  • get the length of that list
  • get the individual x and y values to manipulate

The list I am trying to manipulate can be seen below:

dataTan = Table[{x, Tan[x]}, {x, -1.5, 1.5, .75}];

this question is a sort of a follow-up to the question seen here. I eventually want to write my own function in mathematica that generates the Lagrange Interpolation polynomial for a given set of points

 {{x0, y0}, ... , {xn, yn}}

I need some way to access the points above so that I may utilize the code below:

Sum[Subscript[y, j]*Product[If[j != m, (x - Subscript[x, m])/
       (Subscript[x, j] - Subscript[x, m]), 1], {m, 0, k}], {j, 0, k}]

回答1:


Given your last question, I'm guessing that you mean a Lagrange Polynomial, so

LagrangePoly[pts_?MatrixQ, var_: x] /; MatchQ[Dimensions[pts], {_, 2}] := 
   With[{k = Length[pts]}, Sum[pts[[j, 2]] Product[
     If[j != m, (var - pts[[m, 1]])/(pts[[j, 1]] - pts[[m, 1]]), 1], 
     {m, 1, k}], {j, 1, k}]]

We can test it against the tangent function,

In[2]:= points = Table[{x, Tan[x]}, {x, -1.2, 1.2, .2}]
Out[2]= {{-1.2, -2.57215}, {-1., -1.55741}, {-0.8, -1.02964}, 
         {-0.6, -0.684137}, {-0.4, -0.422793}, {-0.2, -0.20271}, 
         {0., 0.}, {0.2, 0.20271}, {0.4, 0.422793}, 
         {0.6, 0.684137}, {0.8, 1.02964}, {1., 1.55741}, {1.2, 2.57215}}

In[3]:= Plot[Evaluate[Expand[LagrangePoly[points, x]]], {x, -1.2, 1.2}, 
     Epilog -> Point[points]]

In this case, the interpolation is good, the maximum deviation from the original function is

In[4]:= FindMaximum[{Abs[Tan[x] - LagrangePoly[points, x]], -1.2<x<1.2}, x]   
Out[4]= {0.000184412, {x -> 0.936711}}

Also note, that interpolating polynomials are actually built into Mathematica:

In[5]:= InterpolatingPolynomial[points, x]-LagrangePoly[points, x]//Expand//Chop
Out[5]= 0

I had to expand them both before comparison, since InterpolatingPolynomial returns the result in the efficient HornerForm, while my LagrangePoly is returned in a very inefficient form.




回答2:


If you have a list lthen you can get the length of that list by using First@Dimensions@l. Assuming that the list has the form {{x1,y1},{x2,y2},...} you can then get any of the x and y values at position index just by using Part[l,index] or its shorthand l[[index]].

EDIT: If you want to do things the simple way you could conceivably use Length@l for the length of the list.



来源:https://stackoverflow.com/questions/8410613/list-manipulation-in-mathematica-pertaining-to-lagrange-interpolation-polynomial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!