天天看點

龍貝格求積公式 c語言實作 數值積分龍貝格求積公式 c語言實作 數值積分

龍貝格求積公式 c語言實作 數值積分

标簽:計算方法實驗

/*
    本實驗用龍貝格求積公式求4 / (1 + x^2)在[0, 1]的定積分。
*/
#include <stdio.h>
#include <math.h>

double f(double x){
    return  / ( + x * x);
}

int main(){
    double a = , b = , eps = ;  //上下限,精度
    double s, x, s1, s2, c1, c2, r1, r2, h = b - a, t1 = h * (f(a) + f(b)) / , t2, temp;
    int k = ;

    do{
        s = , x = a + h / ;
        do{
            s += f(x);
            x += h;
        }while(x < b);
        t2 = (t1 + h * s) / ;
        s2 = t2 + (t2 - t1) / ;
        if(k == )  {t1 = t2, s1 = s2, h /= , k += ;  continue;}
        c2 = s2 + (s2 - s1) / ;
        if(k == )  {t1 = t2, s1 = s2, c1 = c2, h /= , k += ;  continue;}
        r2 = c2 + (c2 - c1) / ;
        if(k == )  {t1 = t2, s1 = s2, c1 = c2, r1 = r2, h /= , k += ;  continue;}
        temp = r1, r1 = r2, t1 = t2, s1 = s2, c1 = c2, h /= , k += ;
    }while(fabs(r1 - temp) >= eps);  //即fabs(r2 - r1) >= eps
    printf("answer = %f\n", r2);
    return ;
}
           

實驗結果

龍貝格求積公式 c語言實作 數值積分龍貝格求積公式 c語言實作 數值積分