牛顿向后插值(c++附注释)

数值分析/计算方法,欢迎交流讨论

#include <iostream>
#include <math.h>
using namespace std;
double x[100],y[100],f[100][100];//x数组存放节点横坐标,y数组存放节点纵坐标,f数组存放差分表
double factorial(int a)
{
	double b=1;
	for(int i=a;i>0;i--)
		b=b*i;
	return b;
}//编写阶乘函数
double Derivative(double c)
{    double b;
     b=sin(c);
	 return c;
     };//y关于x的n+1阶导数,需要根据具体的题目编写,在下面求截断误差是会用到
double Newtonbackward(double test,int count)//test为要预测值的横坐标,count为节点个数
{
	
	for(int i=0;i<count-1;i++)
		f[0][i]=y[i+1]-y[i];//计算一阶向后差分
	for(int i=1;i<count-1;i++)
	{
		for(int j=count-1;j>=0;j--)
		f[i][j]=f[i-1][j+1]-f[i-1][j];
	}//计算差分表
	double h=x[1]-x[0];//计算步长
	double N=y[count-1];//牛顿向后插值公式的yn
	double T=1;
	double t=(test-x[count-1])/h;
	for(int i=0;i<count;i++)
	{
		T=T*(t+i);
		N=N+T/(factorial(i+1))*f[i][count-2-i];//表示牛顿向后插值公式
	}
	
	double R;//计算截断误差
	T=T*(t+count-1);
	R=abs(T/factorial(count)*pow(h,count)*Derivative(x[count-1]));//要先根据具体题目编写出y关于x的n+1阶导数才能正常计算,下面再将R输出(cout一下)
	cout<<"截断误差为:"<<R<<endl;
	return N;
}
int main()
{
	char ch='n';
	while(ch!='q')
  {
	int count;
	cout<<"请输入节点个数:";
	cin>>count;
    cout<<"请依次输入"<<count<<"个节点的横纵坐标:"<<endl;
	for(int i=0;i<count;i++)
		cin>>x[i]>>y[i];//输入节点坐标
	double test;
	cout<<"请输入要预测值的横坐标:";
	cin>>test;
	cout<<Newtonbackward(test,count);
	cout<<"是否继续?按q退出,按其他字母继续:";
	cin>>ch;
   }
	system("pause");
    return 0;
}

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值