1、拉格朗日差值法:
#include"stdio.h"
#include"math.h"
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
double largrange(x,y,n,x0)
int n;
double *x,*y,x0;
{
int k,j;
double Y=0,p;
for(k=0;k<n;k++)
{
p=1.0;
for(j=0;j<n;j++)
if(j!=k) p*=(x0-x[j])/(x[k]-x[j]);
Y+=p*y[k];
}
return Y;
}
main()
{
double x1[2]={11,12},y1[2]={2.3979,2.4849},
x2[3]={11,12,13},y2[3]={2.3979,2.4849,2.5649},x0=11.75,Y1,Y2;
Y1=largrange(x1,y1,2,x0);
Y2=largrange(x2,y2,3,x0);
printf("Y1=%f\nY2=%f\n",Y1,Y2);
}
2、牛顿差值法:
#include"stdio.h"
#include"math.h"
double Newton(x,y,n,x0)
int n;
double *x,*y,x0;
{
int i,j;
double Y,p;
for(i=1;i<=n;i++)
for(j=n;j>=i;j--)
y[j]=(y[j]-y[j-1])/(x[j]-x[j-i]);
Y=y[0];
for(i=1;i<=n;i++)
{
p=y[i];
for(j=0;j<i;j++)
p*=(x0-x[j]);
Y+=p;
}
return Y;
}
main()
{
double x1[2]={11,12},y1[2]={2.3979,2.4849},
x2[3]={11,12,13},y2[3]={2.3979,2.4849,2.5649},x0=11.75,Y1,Y2;
Y1=Newton(x1,y1,1,x0);
Y2=Newton(x2,y2,2,x0);
printf("Y1=%f\nY2=%f\n",Y1,Y2);
} 转载于:https://blog.51cto.com/lucky/19408