通过梯形规则进行数值积分的通用函数

Passing generic function for numerical integration with trapezoidal rule

我有一种使用梯形法则计算函数积分的方法。它工作正常:

double trap_method(double a, double b, double n){

    int i = 1; double area = 0; double h = (b-a)/(n-1);
    double x = a+h;
    while(i <= n-2){

        area = area + exp(x)*h;
        x = x+h;
        i++;
    }
    area = area + (exp(a) + exp(b)) * h/2;

    return area;
}

但是,如您所见,它仅适用于 ex 或您硬编码到其中的任何内容。

我想知道如何向 trap_method 添加参数,这样我每次都可以更改我想要集成的表达式。类似于:

double trap_method(double a, double b, double n, function f){

    int i = 1; double area = 0; double h = (b-a)/(n-1);
    double x = a+h;
    while(i <= n-2){

        area = area + f(x)*h;
        x = x+h;
        i++;
    }
    area = area + (f(a) + f(b)) * h/2;

    return area;
}

您可以使用函数指针或模板来传递 lambda 函数。

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

double trap_method(double a, double b, int n, double (*func)(double)){

    int i = 1; double area = 0; double h = (b-a)/(n-1);
    double x = a+h;
    while(i <= n-2){

        area = area + func(x)*h;
        x = x+h;
        i++;
    }
    area = area + (func(a) + func(b)) * h/2;

    return area;
}

template<typename FUNC>
double trap_method(double a, double b, int n, FUNC func){

    int i = 1; double area = 0; double h = (b-a)/(n-1);
    double x = a+h;
    while(i <= n-2){

        area = area + func(x)*h;
        x = x+h;
        i++;
    }
    area = area + (func(a) + func(b)) * h/2;

    return area;
}

主要

cout << trap_method(0, 1, 100, f) << endl;
cout << trap_method(0, 1, 100, [](double x){return x*x;}) << endl;
template<typename func_type>
double trap_method(double a, double b, double n, func_type f){

    int i = 1; double area = 0; double h = (b-a)/(n-1);
    double x = a+h;
    while(i <= n-2){

        area = area + f(x)*h;
        x = x+h;
        i++;
    }
    area = area + (f(a) + f(b)) * h/2;

    return area;
}

然后……

double result = trap_method(a, b, n, std::exp);