使用c中的梯形规则进行积分

时间:2016-03-17 13:58:59

标签: c integration numerical-integration

我目前遇到的问题是我开发的程序,用于计算函数1/((1+x^2)(x^(2/3)))的从0到无穷大的积分值。我的代码如下:

#include <stdio.h>
#include <math.h>
#include <float.h>

double integral_Function(double x){ //Define a function returning a double, this funtion calculates f(x) for a given x value
    double value;
    value = 1/((1+ pow(x, 2))*(pow(x, (2/3)))); //pow(x, 2) = x^2
    return value;
}

double trapezium_Rule(double lower, double upper, int n){ //Define a function containing an algorithm for the trapezium rule

    double h;
    double total;
    int i;

    h = (upper - lower)/n; //h = strip width

    total = (h/2) * (integral_Function(upper) + integral_Function(lower)); // Add the two end points

    for(i = 1; i < n; i++){
    total += (h * integral_Function(lower + (i * h))); //add the volume of each of the middle points to the total
    }

    return total;

}

int main() {

    double sum = 0;
    double upper = DBL_EPSILON * 1.001; //DBL_EPSILON is the smallest non-zero value of a double
    double lower = DBL_EPSILON;
    int accuracy;

    printf("Enter the degree of accuracy required: \n");
    scanf("%d", &accuracy);

    while (upper <= DBL_MAX){
        sum +=  trapezium_Rule(lower, upper, 2000);
        lower = upper;
        upper = upper * 1.02;
    }

    printf("The Integral = %.*f to %d decimal places.", accuracy,sum, accuracy);

    return 0;
}

在我的程序中,使用int main()中的while循环将积分分成许多小块,我已经为每个积分指定了条带数。

目前我的代码产生的答案恰好是应有的一半,但是我看不出这个问题出现在哪里。它还会为其他函数生成不正确的值。

0 个答案:

没有答案