数值分析/计算方法,欢迎交流讨论
#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;
}