#include<iostream>
#include<cmath>
using namespace std;void Linear_interpolation(double *x, double *y, double input);//分段线性插值
void Quadratic_interpolation(double *x,double *y,double u);//分段二次插值
void Lagrange_interpolation(double *x, double *y, double xx);//拉格郎日插值int main()//主函数
{double x[6]={0.0, 0.1, 0.195, 0.3, 0.401, 0.5};double y[6]={0.39894, 0.39695, 0.39142, 0.38138, 0.36812, 0.35206};double u;while(cin>>u){Linear_interpolation(x,y,u); //分段线性插值 Quadratic_interpolation(x,y,u); //分段二次插值Lagrange_interpolation(x,y,u); //拉格郎日插值} }void Linear_interpolation(double *x, double *y, double input)//分段线性插值
{double output; for (int i=0;i<5;i++) { if (x[i] <= input && x[i+1] >= input) { output=y[i] +(y[i+1]-y[i])*(input-x[i])/(x[i+1]-x[i]); break; } } cout<<"Linear_interpolation: "<<output<<endl;
}void Quadratic_interpolation(double *x,double *y,double u)//分段二次插值
{int i,k=0; double v; for(i=0;i<6;i++) { if(u<x[1]) { k=0; v=y[k]*(u-x[k+1])*(u-x[k+2])/((x[k]-x[k+1])*(x[k]-x[k+2]))+y[k+1]*(u-x[k])*(u-x[k+2])/((x[k+1]-x[k])*(x[k+1]-x[k+2]))+y[k+2]*(u-x[k])*(u-x[k+1])/((x[k+2]-x[k])*(x[k+2]-x[k+1])); } if((x[i]<u&&u<=x[i+1])&&(fabs(u-x[i])<=fabs(u-x[i+1]))) { k=i-1; v=y[k]*(u-x[k+1])*(u-x[k+2])/((x[k]-x[k+1])*(x[k]-x[k+2]))+y[k+1]*(u-x[k])*(u-x[k+2])/((x[k+1]-x[k])*(x[k+1]-x[k+2]))+y[k+2]*(u-x[k])*(u-x[k+1])/((x[k+2]-x[k])*(x[k+2]-x[k+1])); } if ((x[i]<u&&u<=x[i+1])&&fabs(u-x[i])>fabs(u-x[i+1])) { k=i; v=y[k]*(u-x[k+1])*(u-x[k+2])/((x[k]-x[k+1])*(x[k]-x[k+2]))+y[k+1]*(u-x[k])*(u-x[k+2])/((x[k+1]-x[k])*(x[k+1]-x[k+2]))+y[k+2]*(u-x[k])*(u-x[k+1])/((x[k+2]-x[k])*(x[k+2]-x[k+1])); } if(u>x[4]) { k=3; v=y[k]*(u-x[k+1])*(u-x[k+2])/((x[k]-x[k+1])*(x[k]-x[k+2]))+y[k+1]*(u-x[k])*(u-x[k+2])/((x[k+1]-x[k])*(x[k+1]-x[k+2]))+y[k+2]*(u-x[k])*(u-x[k+1])/((x[k+2]-x[k])*(x[k+2]-x[k+1])); } } cout<<"Quadratic_interpolation: "<<v<<endl;
}void Lagrange_interpolation(double *x, double *y, double xx)//拉格郎日插值
{int i,j; double *a, yy=0.000; a=new double[6]; for(i=0;i< 6;i++) { a[i]=y[i]; for(j=0;j< 6;j++) if(j!=i) a[i]*=(xx-x[j])/(x[i]-x[j]); yy+=a[i]; } delete a; cout<<"Lagrange_interpolation: "<<yy<<endl;
}
详细解决方案
线性插值 二次插值 拉格郎日插值
热度:2 发布时间:2023-12-04 20:07:30.0