分段插值(C++附注释)

数值分析/计算方法,欢迎交流

#include <iostream>
using namespace std;
double x[100],y[100];//存放节点的横坐标和纵坐标
double f2,f3;
double quadratic_interpolation(int count,double test,double x[])
{
	int a;
	a=0;
	for(int i=0;i<count;i++)
		{if(x[i]<test)
		a=i;}
	f2=y[a]*(test-x[a+1])/(x[a]-x[a+1])+y[a+1]*(test-x[a])/(x[a+1]-x[a]);
	return f2;
}//分段二次插值算法
double parabolic_interpolation(int count,double test,double x[])
{
	int b;
	if(test>=x[0]&&test<0.5*(x[1]+x[2]))
		b=1;
	for(int j=1;j<count;j++)
		if(test>=0.5*(x[j-1]+x[j])&&test<0.5*(x[j]+x[j+1]))
			b=j;
	if(test>=0.5*(x[count-3]+x[count-2])&&test<=x[count-1])
		b=count-2;
	f3=(test-x[b])*(test-x[b+1])/(x[b-1]-x[b])/(x[b-1]-x[b+1])*y[b-1]+(test-x[b-1])*(test-x[b+1])/(x[b]-x[b-1])/(x[b]-x[b+1])*y[b]+
		(test-x[b-1])*(test-x[b])/(x[b+1]-x[b-1])/(x[b+1]-x[b])*y[b];
	return f3;
}//分段抛物插值算法
int main()
{
	int count;
	cout<<"请输入节点个数:";
	cin>>count;
	cout<<"请依次输入节点的横坐标和纵坐标:"<<endl;
	for(int i=0;i<count;i++)
		cin>>x[i]>>y[i];
	double test;
	cout<<"请输入要预测值的横坐标:";
	cin>>test;
	double tx,ty;
	for(int i=0;i<count;i++)
	{
		for(int j=1;j<count-i;j++)
			if(x[j-1]>x[j])
			{
				tx=x[j-1];
				x[j-1]=x[j];
				x[j]=tx;
				ty=y[j-1];
				y[j-1]=y[j];
				y[j]=ty;
			}
	}//对节点排序,使其按照横坐标依次增大的顺序排列,便于接下来遍历确定插值区间
	char ch='n';
	while(ch!='q')
	{
	int interpolation;
	cout<<"请输入插值次数(分段线性插值为1,分段抛物插值为2):";
	cin>>interpolation;
	if(interpolation==0||interpolation>2)
	{   cout<<"只支持二次插值和抛物插值,请重新输入:";
		cin>>interpolation;
	}
	f2=quadratic_interpolation(count,test,&x[100]);
	f3=parabolic_interpolation(count,test,&x[100]);
	if(interpolation==1)
		cout<<"分段线性插值后的预测结果为:"<<f2<<endl;
	if(interpolation==2)
		cout<<"分段抛物插值后的预测结果为:"<<f3<<endl;
	cout<<"按q退出,按其他字母继续:";
	cin>>ch;
	}
	system("pause");
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值