Chinaunix首页 | 论坛 | 博客
  • 博客访问: 926603
  • 博文数量: 146
  • 博客积分: 3321
  • 博客等级: 中校
  • 技术积分: 1523
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-29 10:32
文章分类

全部博文(146)

文章存档

2014年(2)

2013年(5)

2012年(4)

2011年(6)

2010年(30)

2009年(75)

2008年(24)

分类: C/C++

2009-10-07 12:12:07

拉格朗日差值法公式结构紧凑,但是当差值几点增减时全部差值基函数都得改变。牛顿差值法则不需要改变,而且可以利用已经计算出来的均差去计算新的均差。为了进行比较我将Newton差值法和Lagrange差值法写在了同一个程序中。
程序实现:

/*
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;
}


   我这里针对Lagrange差值法设定了可以通过键盘进行差值节点的初始话。Newton差值法这里没有写具体如何从键盘进行初始化,因为这个和Lagrange差值法的初始化方法类似,只是Newton差值法是要使用到二维数组指针。
阅读(4848) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~