分别用1~~4次Lagrange,Newton插值计算函数在0.9处的函数值
i | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|
xi | 0 | 0.17 | 0.65 | 0.85 | 1 |
分别用1~~4次Lagrange,Newton插值计算函数在0.9处的函数值
Lagrange
-
插值基函数
image1.png - Lagrange插值多项式
image2.png
[图片来源]: https://blog.csdn.net/u013871100/article/details/41249285
Newton
-
均差
image3.png
image4.png - Newton插值多项式
image5.png
[图片来源]:https://blog.csdn.net/Gy_1096440940/article/details/78445088
#include <iostream>
using namespace std;
//求yi的值
float Evaluation(float x)
{
return 1/(1+25*x*x);
}
//Lagrange
float Lagrange(float x,int n,float a[],float b[])
{
float t,y=0;
int j,k;
for (k = 0;k <= n;k++)
{
t = 1;
for (j = 0;j <= n;j++)
{
if (j != k)
t = ((x - a[j])/(a[k]-a[j]))*t;
}
y = t * b[k]+y;
}
return y;
}
// Newton均差
void AverageDeviation(int n,float ad[][100],float a[],float b[])
{
int i,j;
for (i = 0;i <= n; i++)
{
ad[i][0] = b[i];
for (j = 1;j <= n; j++)
{
if(j>i)
ad[i][j] = 0;
else
{
ad[i][j] = (ad[i-1][j-1]-ad[i][j-1])/(a[i-j]-a[i]);
}
}
}
}
//Newton
float Newton(int n,float x,float a[],float b[],float ad[][100])
{
int i,j;
float y=ad[0][0];
float p;
for (i=1;i<=n;i++)
{
p=ad[i][i];
for(j=0;j<=i-1;j++)
p *= (x-a[j]);
y += p;
}
return y;
}
int main()
{
float x,a[100],b[100];
float ad[100][100];
int i,j,k,n;
cout << "输入插值次数n:"<<endl;
cin >> n;
cout << "输入你要估算对象xֵ:"<<endl;
cin >> x;
for (i=0;i<=n;i++)
{
cout<< "输入x"<<i<<"的值:";
cin >> a[i];
b[i] = Evaluation(a[i]);
cout<< "输入y"<<i<<"的值:"<<b[i]<<endl;
}
cout << "Lagrange得y = "<< Lagrange(x,n,a,b)<<endl;
// 调用函数求Newton均差
AverageDeviation(n,ad,a,b);
for(i=0;i<=n;i++)
{
cout<<"第"<<i<<"阶均差为:"<<ad[i][i]<<endl;
}
cout << "Newton得y = "<< Newton(n,x,a,b,ad)<<endl;
return 0;
}
网友评论