/*
author:Along meng
Function:根据给定的几个差值节点用Lagrange差值法和Newton差值法进行计算
特定点的值。
*/
#include <stdio.h>
#include <stdlib.h>
/*当INPUT_FLAG等于0时表示直接在程序里进行差值节点的初始化
**当INPUT_FLAG不等于0时表示从键盘输入差值节点
*/
#define INPUT_FLAG 0
void initarray(float *x, float *y, int n); /*初始化数组*/
/*Lagrange差值法计算*/
float calculate_lagrange(float *x, float *y, int n, float xx);
/*Newton差值法*/
float calculate_newton(float *x, float *y, int n, float xx);
int main(void)
{
int n; /*记录差值节点的个数*/
#if INPUT_FLAG
float *x, *y;
#else
float x[5] = {0.4, 0.55, 0.8, 0.9, 1};
float y[5] = {0.41075, 0.57815, 0.88811, 1.02652, 1.17520};
n=5; /*n的值要根据差值节点的个数定*/
#endif
float xx, yy; /*要进行计算的点*/
int i, j;
#if INPUT_FLAG
printf("input n:");
scanf("%d", &n);
x=(float *)malloc(sizeof(float)*n);
y=(float *)malloc(sizeof(float)*n);
initarray(x, y, n);
#endif
printf("\ninput the num you want to calculate:");
scanf("%f", &xx);
/*用Lagrange差值法计算*/
yy = calculate_lagrange(x, y, n, xx);
printf("\nLagrange :\n");
printf("(%f, %f)\n", xx, yy);
/*用牛顿差值法进行计算*/
yy = calculate_newton(x, y, n, xx);
printf("Newton :\n");
printf("(%f, %f)\n\n", xx, yy);
return 0;
}
void initarray(float *x, float *y, int n) /*初始化数组*/
{
int i;
for( i = 0; i < n; i++ ) {
printf("\ninput x[%d],y[%d](用逗号隔开):", i, i);
scanf("%f, %f", &x[i], &y[i]);
}
}
float calculate_lagrange(float *x, float *y, int n, float xx)
{
int i, j;
float p, yy=0;
for( i = 0; i < n; i++ ) {
p = 1;
for( j = 0; j < n; j++ ) {
if(i != j) {
p = p * ((xx - x[j]) / (x[i] - x[j]));
}
}
yy = yy + p * y[i];
}
return yy;
}
float calculate_newton(float *x, float *y, int n, float xx)
{
int i, j;
float avg[6][6];
float yy, p;
for(i = 0; i < n; i++) {
avg[i][0] = y[i];
}
yy = avg[0][0];
p = 1;
for(i = 1; i < n; i++) {
for( j = 1; j <= i; j++ ) {
avg[i][j] = (avg[i][j-1] - avg[i-1][j-1]) / (x[i] - x[i-j]);
}
p *= (xx - x[i-1]);
yy += p * avg[i][i];
}
return yy;
}
|