Numerical integration in C++

后端 未结 4 417
Happy的楠姐
Happy的楠姐 2020-12-29 16:21

I need to integrate a function (of two variables). I know I can do it by using Fubini theorem to integrate one variable functions, then using numerical methods such

4条回答
  •  渐次进展
    2020-12-29 16:28

    You might wish to check out the Boost Quadrature and Differentiation Library. In particular, they provide a version of the Trapezoid Rule:

    https://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/trapezoidal.html

    The Quadrature/Differentiation Library is very well written and compatible with modern C++, in that one can just use a lambda expression or a function object for the integrand. I was up and running with it very quickly.

    Here's an example of approximating pi, by approximating the integral of 4/(1 + x^2), from x = 0 to x = 1, putting the integrand as a lambda expression.

    #include 
    #include 
    using boost::math::quadrature::trapezoidal;
    using std::cout;
    using std::endl;
    
    // Put inside a test function:
    auto f = [](double x)
    {
        return 4.0 / (1.0 + x * x);
    };
    
    double appPi = trapezoidal(f, 0.0, 1.0);
    
    double tol = 1e-6;
    int max_refinements = 20;
    double appPi2 = trapezoidal(f, 0.0, 1.0, tol, max_refinements);
    
    cout << "Trapezoid Rule results for computing pi by integration" << endl;
    cout << "a) with defaults, and b) with tol and max_refine set : " << endl;
    cout << appPi << ", " << appPi2 << endl << endl;
    

    I provided two examples, one using the default settings for the discretization of the range of integration and convergence, and the second using custom settings.

    My results (just taking a copy of the output from the screen) are:

    Trapezoid Rule results for computing pi by integration
    a) with defaults, and b) with tol and max_refine set :
    3.14159, 3.14159
    

提交回复
热议问题