问题描述
我正在尝试使用以可以的方式传递给函数的列表
I am trying to use a list which is passed to a function in such a way that I can
- 获取该列表的长度
- 获取单独的x和y值进行操作
我要操作的列表如下所示:
The list I am trying to manipulate can be seen below:
dataTan = Table[{x, Tan[x]}, {x, -1.5, 1.5, .75}];
此问题是对在此处看到的问题的一种后续措施.我最终想要在mathematica中编写自己的函数,该函数针对给定的点集生成拉格朗日插值多项式
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}]
推荐答案
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}]]
我们可以针对切线函数
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}}
还要注意,内插多项式实际上是内置在Mathematica中的: /p>
Also note, that interpolating polynomials are actually built into Mathematica:
In[5]:= InterpolatingPolynomial[points, x]-LagrangePoly[points, x]//Expand//Chop
Out[5]= 0
在比较之前,我必须将它们都展开,因为InterpolatingPolynomial
在高效的 HornerForm
,而我的LagrangePoly
以非常低效的形式返回.
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.
这篇关于与Mathematica中的Lagrange插值多项式有关的Mathematica中的列表处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!