#include <iostream>
using namespace std;
//牛顿插值求解多项式
double * xs; //all input x
double * ys; //all input y
int n; //size
//1 2 3 4
//0 -5 -6 3
//1.5
//-2.625
void init()
{
cout << "please input n " << endl;
cin >> n;
xs = new double[n];
ys = new double[n];
//input x
cout << "please input the x‘s value !" << endl;
for(int i=0; i<n; i++)
{
cin >> xs[i];
}
//input y
cout << "please input the y‘s value !" << endl;
for(int i=0; i<n; i++)
{
cin >> ys[i];
}
}
double f(int n)
{
double f=0;
double temp=0;
for(int i=0; i<n+1; i++)
{
temp=ys[i];
for(int j=0; j<n+1; j++)
{
if(i!=j)
temp /= (xs[i]-xs[j]);
}
f += temp;
}
return f;
}
double newton(double x)
{
double result=0;
for(int i=0; i<n; i++)
{
double temp=1;
double fi=f(i);
for(int j=0; j<i; j++)
{
temp = temp*(x-xs[j]);
}
result += fi*temp;
}
return result;
}
int main()
{
init();
double x;
cout << "please input the x‘ value !" << endl;
cin >> x;
cout << "the result of the Newton is " << newton(x);
return 0;
}
附件列表
时间: 2024-10-17 13:27:08