数值计算实验三——拉格朗日插值和牛顿插值

//拉格朗日插值
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100;
double x[maxn],y[maxn];
double l[maxn];
int main(){
	x[0]=0.56160;x[1]=0.56280;
	x[2]=0.56401;x[3]=0.56521;
	y[0]=0.82741;y[1]=0.82659;
	y[2]=0.82577;y[3]=0.82495;
	double resx=0.56350,resy=0;
	double cnt1=1,cnt2=1;
	int n=3;
	for(int i=0;i<=n;i++){
		cnt1=1,cnt2=1;
		for(int j=0;j<=n;j++){
			if(i==j) continue;
			cnt1=cnt1*(resx-x[j]);
			cnt2=cnt2*(x[i]-x[j]);
		}
		l[i]=cnt1/cnt2;
		resy=resy+y[i]*l[i];
	}
	cout<<resy<<endl;
	return 0;
}
//牛顿插值
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100;
double x[maxn],y[maxn];
double a[maxn][maxn];
int main(){
	x[0]=0.56160;x[1]=0.56280;
	x[2]=0.56401;x[3]=0.56521;
	y[0]=0.82741;y[1]=0.82659;
	y[2]=0.82577;y[3]=0.82495;
	double resx=0.56350,resy=0;
	double cnt1=1,cnt2=1;
	int n=4;
	for(int j=0;j<=n-1;j++)///列
		for(int i=j;i<=n-1;i++)
			if(!j) a[i][j]=y[i];
			else a[i][j]=(a[i][j-1]-a[i-1][j-1])/(x[i]-x[i-j]);	 
	double tmp=1;
	for(int i=0;i<=n;i++){
		if(i) tmp=tmp*(resx-x[i]);
		resy=resy+a[0][i]*tmp;
	}
	cout<<resy<<endl;
	return 0;
}
posted @ 2020-10-19 17:13  OvO1  阅读(160)  评论(0编辑  收藏  举报