The Method
In[1]:=
x={1,2.7,3.2,4.8,5.6}
y={14.2,17.8,22,38.3,51.7}
Out[1]=
{1, 2.7, 3.2, 4.8, 5.6}
Out[2]=
{14.2, 17.8, 22, 38.3, 51.7}
We can use a Lagrangian polynomial of degree 4, P4. The following function will return the Lagrangian polynomial of degree one less than the number of points. By the way, if you want a lesser degree, simply disregard some of the points.
In[3]:=
lagrangepoly[t_,x_,y_]:=
Module[{n,poly,q,i,j},
n=Dimensions[x][[1]];poly=0;
For[i=1,i<=n,i++,
q=1;
For[j=1,j<=n,j++,
If[j!=i,q=q*(t-x[[j]])/(x[[i]]-x[[j]])]
];
poly=poly+q*y[[i]];
];
poly
];
In[4]:=
p4[t_]:=lagrangepoly[t,x,y]
In[5]:=
p4[t]
Out[5]=
0.217208 (-5.6 + t) (-4.8 + t) (-3.2 + t) (-2.7 + t) -
3.43862 (-5.6 + t) (-4.8 + t) (-3.2 + t) (-1 + t) +
5.20833 (-5.6 + t) (-4.8 + t) (-2.7 + t) (-1 + t) -
3.74961 (-5.6 + t) (-3.2 + t) (-2.7 + t) (-1 + t) +
2.01852 (-4.8 + t) (-3.2 + t) (-2.7 + t) (-1 + t)
Do you trust the Lagrange polynomial? Let's evaluate it at the x values and see if the match the y values.
In[6]:=
test=p4[x]
y
Out[6]=
{14.2, 17.8, 22., 38.3, 51.7}
Out[7]=
{14.2, 17.8, 22, 38.3, 51.7}
To convince you that the Lagrange polynomial is an easy way to fit points, let's look more closely at its definition:
In[8]:=
x={x1,x2,x3,x4,x5}
y={y1,y2,y3,y4,y5}
Out[8]=
{x1, x2, x3, x4, x5}
Out[9]=
{y1, y2, y3, y4, y5}
In[10]:=
p4[t_]:=lagrangepoly[t,x,y]
In[11]:=
p4[t]
Out[11]=
(t - x2) (t - x3) (t - x4) (t - x5) y1
--------------------------------------- +
(x1 - x2) (x1 - x3) (x1 - x4) (x1 - x5)
(t - x1) (t - x3) (t - x4) (t - x5) y2
---------------------------------------- +
(-x1 + x2) (x2 - x3) (x2 - x4) (x2 - x5)
(t - x1) (t - x2) (t - x4) (t - x5) y3
----------------------------------------- +
(-x1 + x3) (-x2 + x3) (x3 - x4) (x3 - x5)
(t - x1) (t - x2) (t - x3) (t - x5) y4
------------------------------------------ +
(-x1 + x4) (-x2 + x4) (-x3 + x4) (x4 - x5)
(t - x1) (t - x2) (t - x3) (t - x4) y5
-------------------------------------------
(-x1 + x5) (-x2 + x5) (-x3 + x5) (-x4 + x5)
Now do you see why this works? (And works easily!)