#include<iostream>
#include<iomanip>
using namespace std;
// 差商表
class DiffQuot{
public:
double *xk;
double *fxk;
double **order;//差商 列 xk f(xk) 一阶均差 二阶...
int n;// 点的个数 从0开始计数
DiffQuot(double* xk, double *fxk, int n_):n(n_),xk(xk),fxk(fxk){
order = new double*[n];
// 一阶均差
order[0] = new double[n];
for(int j = 0; j < n; j++){
order[0][j] = (fxk[j+1] - fxk[j]) / (xk[j+1] - xk[j]);
}
// 二阶均差...
for(int i = 1; i < n; i++){
order[i] = new double[n - i];
for(int j = 0; j < n - i; j++){
order[i][j] = (order[i-1][j+1] - order[i-1][j]) / (xk[j+i+1] - xk[j]);
}
}
}
void showOrderList(){
cout<<fixed<<setprecision(5);
for(int i = 0; i < n + 1; i++){
cout<<xk[i]<<"\t"<<fxk[i]<<"\t";
for(int j = 0; j < n - i; j++){
cout<<order[j][i]<<"\t";
}
cout<<endl;
}
}
double getNx(double x){
double* x_xk = new double[n];
for(int i = 0; i < n; i++){
x_xk[i] = x - xk[i];
}
double result = fxk[0];
for(int i = 0; i < n; i++){
double temp = order[i][0];
for(int j = 0; j <= i; j++){
temp *= x_xk[j];
}
result += temp;
}
return result;
}
};
int main(){
//Point(0.4,0.41075),Point(0.55,0.57815),Point(0.8,0.88811),Point(0.9,1.02652),Point(1,1.17520)
double xk[] = {0.4,0.55,0.8,0.9,1};
double fxk[] = {0.41075,0.57815,0.88811,1.02652,1.17520};
DiffQuot dq(xk, fxk, 4);
dq.showOrderList();
cout<<endl;
cout<<fixed<<setprecision(6);
cout<<dq.getNx(0.5)<<endl;
cout<<dq.getNx(0.7)<<endl;
cout<<dq.getNx(0.85)<<endl;
return 0;
}
【计算方法实验】实验6:牛顿插值
最新推荐文章于 2022-04-18 22:37:10 发布