Newton插值

举例:

题目:
被插值函数与被插值区间为: f ( x ) = 1 1 + 25 x 2 f(x)=\frac{1}{1+25x^2} [ a , b ] = [ 0 , 1 ] [a,b]=[0,1] ,若插值点为:

i i 1 2 3 4 5
x i x_i 0 0.17 0.65 0.85 1

用1~4次Newton插值计算函数在0.9处的函数值

Newton插值代码:

#include<iostream> 
#include<string> 
#include<vector>  //动态矩阵
using namespace std;

double DevidedDifference(int n, vector<double>&X, vector<double>&Y);//差商
double Newton(double xp, vector<double>&X, vector<double>&Y); 

int main()
{	
	int n;
	while(cin>>n)
	{
		vector<double>X(n, 0);//声明一个初始大小为n且初始值都为0的向量	
		vector<double>Y(n, 0);		
		cout << "\n请输入插值点X[i]的值" << endl;	
		for (int i = 0; i<n; i++)	
		{		
		     cin >> X[i] ;	
		}	
		cout << "\n计算得Y[i]的值" << endl;	
		for (i = 0; i<n; i++)	
		{
             Y[i]=1/(1+25*X[i]*X[i]);	
             cout<<Y[i]<<endl;//輸出Y[i],方便進行Lagrange插值
		}	

		cout << "\n输入要计算的函数点x " << endl;
        double xp;	
		cin >> xp;	
        double result=Newton(xp, X, Y);	
		cout << "\n输出所求插值点的函数值:" << endl;
	                cout<< result<<endl;
	}	
	return 0;
} 
double DevidedDifference(int n, vector<double>&X, vector<double>&Y)
{	
	double f = 0;	
    double temp = 0;	
	for (int i = 0; i<n; i++)
	{		
		temp = Y[i];	
		for (int j = 0; j<n; j++)			
		        if (i != j)
                     temp /= (X[i] - X[j]);	
		 f += temp;	
}	
	return f;
}
double Newton(double xp, vector<double>&X, vector<double> &Y)
{	
	double temp1 = 0,result;	
	for (int i = 0; i<X.size(); i++)		
	{
		double temp = 1;			
		double f = DevidedDifference(i+1, X, Y);		
		for (int j = 0; j < i; j++)			
	{				
		temp = temp*(xp - X[j]);		
	}
		temp1 += f*temp;		
	}		
	result= temp1;	
	temp1 = 0;	
	return result;
 }

运行结果:
在这里插入图片描述

发布了42 篇原创文章 · 获赞 30 · 访问量 7202

猜你喜欢

转载自blog.csdn.net/Mr____Cheng/article/details/102882194