//Author:DengJin #include<stdio.h>
#include<stdarg.h>
#include<stdlib.h>
double Lagrange(double x,/*需要知道函数值的节点坐标*/
int n,/*已知坐标的个数*/
...);/*可变动参数获取各已知节点和其值*/
int
main(void){
/*for testing*/
double value = Lagrange(1.5,5,1.0,1.3,1.6,1.9,2.2,0.7651977,0.6200860,0.4554022,0.2818186,0.1103623);
/*以上用f(1.0) = 0.7651977
f(1.3) = 0.6200860等等进行测试*/
printf("%9.7lf\n",value);
system("pause");
return EXIT_SUCCESS;
}
double Lagrange(double x,
int n,
...){
int i = 0,j = 0;
double *px = malloc(sizeof(double)*n);
double *py = malloc(sizeof(double)*n);
double result = 0;
double *ppx = px,*ppy = py;
double numerator = 1,denominator = 1;
va_list arg;
va_start(arg,n);
for(i=0;i<n;i++)
*ppx++ = va_arg(arg,double);/*获取已知节点X坐标 */
for(i=0;i<n;i++)
*ppy++ = va_arg(arg,double);/*获取已知节点函数值 */
va_end(arg);
for(i=0;i<n;i++){
numerator = denominator = 1;
for(j=0;j<n;j++){
if(i == j) continue;
numerator *= (x-px[j]);
denominator *= (px[i]-px[j]);
/*printf("px[i] = %9.7lf px[j] = %9.7lf\n",px[i],px[j]);
printf("fenzi = %9.7lf fenmu = %9.7lf\n",fenzi,fenmu);*/
}
result += numerator/denominator*py[i];
}
return result;
}
|