利用牛顿的插值公式求出n次插值的结果
//Newton interpolation
//拉格朗日插值Lagrange Interpolation
#include<iostream>
#include<vector>
using namespace std;
//get f(xi,xi+1) value
float getf(vector<float>x,int i,vector<float>y)
{
return (y[i]-y[i-1])/(x[i]-x[i-1]);
}
//get num_node order difference quotient
//n represent n order interpolation
float getDiff_quot(vector<float>x,int pre,int suf,int n,vector<float>y)
{
for(int j=0;j<n;j++)
{
if(n==1)
{
return getf(x,suf,y);
break;
}
return (getDiff_quot(x,1,suf,n-1,y)-getDiff_quot(x,0,suf-1,n-1,y))/(x[suf]-x[pre]);
}
}
float getNutonValue(int n,vector<float>X,float x,vector<float>Y)
{
float temp=1;
float result=Y[0];
//cout<<"f0:"<<result<<endl;
for(int i=1;i<n+1;i++)
{
for(int j=0;j<i;j++)
{
temp*=(x-X[j]);
}
//cout<<"getdiff:"<<getDiff_quot(X,0,i,i,Y)<<endl;
result+=temp*getDiff_quot(X,0,i,i,Y);
temp=1;
}
return result;
}
int main()
{
int num_node;
int i=-1;
cout<<"Please input the number of nodes:"<<endl;
cin>>num_node;
cout<<"-----"<<num_node-1<<" times interpolation----"<<endl;
vector<float>x_var;//store x(i) values
vector<float>y_var;//store y(i) values
x_var.resize(num_node);
y_var.resize(num_node);
cout<<"Please input values x,y of nodes"<<endl;
cout<<"--------------------------------"<<endl;
while(++i<num_node)
{
cout<<"Please input x_var["<<i<<"]:"<<endl;
cin>>x_var[i];
cout<<"Please input y_var["<<i<<"]:"<<endl;
cin>>y_var[i];
}
cout<<"x_var[i]"<<"\t"<<"y_var[i]"<<endl;
for(i=0;i<num_node;i++)
cout<<x_var[i]<<"\t\t"<<y_var[i]<<endl;
cout<<"-------------------------------"<<endl;
float x;
cout<<"PLease input a value x:"<<endl;
cin>>x;
//cout<<"2 oder interpolation:"<<getDiff_quot(x_var,0,num_node,num_node-1,y_var)<<endl;
cout<<"-------------------------------"<<endl;
cout<<"The result of Nuton interpolation when x="<<x<<" is:"<<getNutonValue(num_node-1,x_var,x,y_var)<<endl;
//cout<<"n=1:"<<getf(x_var,1,y_var)<<endl;
cout<<"-------------------------------"<<endl;
cout<<"Hello Boker..."<<endl;
system("pause");
return 0;
}
结果如下: