如何在C++中计算定积分

How to compute a definite Integral in C++?

本文关键字:计算 C++      更新时间:2023-10-16

如何定义一个函数来计算C++中定积分的值?例如求解函数x^2 * cos(x)的积分?

有趣的是,我不久前看到了这篇文章,解释了一种使用函数指针计算数值积分的方法。

https://helloacm.com/c-function-to-compute-numerical-integral-using-function-pointers/

对于类似 x^2 * cos(x) 的东西:

你需要一个重载的积分函数:

double integral(double(*f)(double x), double(*g)(double x, double y), double a, double b, int n)
{
    double step = (b - a)/n;   // width of rectangle
    double area = 0.0;
    double y = 0;  // height of rectangle
    for(int i = 0; i < n; ++i)
    {
        y = f(a + (i + 0.5) * step) * g(a + (i + 0.5) * step, y);
        area += y * step  // find the area of the rectangle and add it to the previous area. Effectively summing up the area under the curve.
    }
    return area;
}

要调用:

int main()
{
    int x = 3;
    int low_end = 0;
    int high_end = 2 * M_PI;
    int steps = 100;
    cout << integral(std::powf, std::cosf, low_end, high_end, steps);
    return 0;
}