Lagrange插值法并不是十分实用的插值法,通常是在分段插值中使用,当插值结点过多时,会出现数据不稳定的龙格现象.
#include "Lagrange.h"
#include "myAssert.h"
#include <stdlib.h>
#include <stdio.h>
Type lagrangeInsert(Type *xArr,Type *yArr,Type x,int n)
{
Type tmpSum=Type_Zero,sum=Type_Zero;
int i=0,j=0;
asserts(xArr!=NULL,"xArr passed in is null\n");
asserts(yArr!=NULL,"yArr passed in is null\n");
for (i=0;i<n;i++)
{
tmpSum=yArr[i];
for(j=0;j<n;j++)
if(j!=i)tmpSum*=(x-xArr[j])/(xArr[i]-xArr[j]);
sum+=tmpSum;
}
return sum;
}
/*test*/
#include "Lagrange.h"
#include "stdio.h"
#include "string.h"
void main()
{
double x1[]={0.4,0.5,0.6,0.7};
double y1[]={-0.916291,-0.693147,-0.510826,-0.356675};
double ans;
clrscr();
ans=lagrangeInsert(x1,y1,0.54,4);//4表示所插值出的是四次多项式.
printf("The answer of lagrangeInsert is:%f\n",ans);
}