计算机辅助设计(插值法程序)
计算机辅助设计上机作业
例:已知列表函数,求X=0.57891处的函数值。
X0.40.50.60.70.80.9Y0.389420.479430.564640.644220.717360.80341
一、线性插值法
1、源程序如下:
#include "stdio.h"
void main()
{
int i,key=0;
double X0,X1,X2,Y0,Y1,Y2;
double X[6]={0.4,0.5,0.6,0.7,0.8,0.9};
double Y[6]={0.38942,0.47943,0.56464,0.64422,0.71736,0.80341};
printf("请输入X0的值(其中X0的范围为0.4-0.9):X0=");
scanf("%lf",&X0);
while(X0<0.4||X0>0.9)
{
printf("\n输入错误!\n\n请重新输入X0的值(其中X0的范围为0.4-0.9):X0=");
scanf("%lf",&X0);
}
for(i=0;i<6;i++)
{
if(X[i]==X0)
{
Y0=Y[i];
key=1;
i=7;
}
}
if(key==0)
{
for(i=0;i<6;i++)
{
if(X[i]>X0)
{
X1=X[i-1];
X2=X[i];
Y1=Y[i-1];
Y2=Y[i];
Y0=Y1+(Y2-Y1)*(X0-X1)/(X2-X1);
i=7;
}
}
}
printf("\nX=%lf,Y=%lf\n",X0,Y0);
}
2、运行结果如下:
二、拉格朗日二次插值
1、源程序如下:
#include "stdio.h"
void main()
{
int i,key=0;
double X0,X1,X2,X3,Y0,Y1,Y2,Y3;
double X[6]={0.4,0.5,0.6,0.7,0.8,0.9};
double Y[6]={0.38942,0.47943,0.56464,0.64422,0.71736,0.80341};
printf("请输入X0的值(其中X0的范围为0.4-0.9):X0=");
scanf("%lf",&X0);
while(X0<0.4||X0>0.9)
{
printf("\n输入错误!\n\n请重新输入X0的值(其中X0的范围为0.4-0.9):X0=");
scanf("%lf",&X0);
}
for(i=0;i<6;i++)
{
if(X[i]==X0)
{
Y0=Y[i];
key=1;
i=7;
}
}
if(key==0)
{
for(i=0;i<6;i++)
{
if(X[i]>X0)
{
if(((X[i]-X0)(X0-X[i-1])&&(i=1)))
{
X1=X[i-1];
X2=X[i];
X3=X[i+1];
Y1=Y[i-1];
Y2=Y[i];
Y3=Y[i+1];
}
else
{
X1=X[i-2];
X2=X[i-1];
X3=X[i];
Y1=Y[i-2];
Y2=Y[i-1];
Y3=Y[i];
}
Y0=Y1*(X0-X2)*(X0-X3)/(X1-X2)/(X1-X3)+Y2*(X0-X1)*(X0-X3)/(X2-X1)/(X2-X3)+Y3*(X0-X1)*(X0-X2)/(X3-X1)/(X3-X2);
i=7;
}
}
}
printf("\nX=%lf,Y=%lf\n",X0,Y0);
}
2、运行结果如下:
4