牛顿插值法

利用牛顿的插值公式求出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;
}


结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值