//牛顿插值算法
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
#define Length 10
double NewtonInterpolation(int n, double* x, double* y, double xi,double newtontime) {
double sinx = 0.0;
double DifQTable[Length][Length] = { 0 };
for (int i = 0; i <= n; i++)
DifQTable[0][i] = y[i];
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
DifQTable[i][j] = (DifQTable[i - 1][j] - DifQTable[i - 1][j - 1]) / (x[j] - x[j - i]);
}
}
for (int i = 0; i <= newtontime; i++) {
double temp = DifQTable[i][i];
for (int j = 0; j < i; j++) {
temp *= xi - x[j];
}
sinx += temp;
}
return sinx;
}
int main() {
int n;
double x[Length], y[Length], xi;
cout << "-------------录入数据-----------" << endl;
cout << "请输入插值节点个数(从0开始):";
cin >> n;
cout << endl;
for (int i = 0; i <= n; i++) {
cout << "x[" << i << "]=";
cin >> x[i];
cout << "y[" << i << "]=";
cin >> y[i];
cout << endl;
}
cout << endl;
cout << "-------------录入完毕------------" << endl;
double newtontime;
cout << "请输入所求newton插值多项式次数:";
cin >> newtontime;
cout << "请输入x的值:";
cin >> xi;
double sinx = NewtonInterpolation(n, x, y, xi, newtontime);
cout << "根据Newton插值多项式计算sin(" << xi << ")=" << sinx << endl;
double error;
error = abs(sinx - sin(xi));
cout << setprecision(1) << "sin(" << xi << ")近似值的绝对误差为:" << error << endl;
system("pause");
return 0;
}
牛顿插值算法的实现
于 2020-11-29 16:20:23 首次发布