trapezoidal_example.cpp 1.1 KB

1234567891011121314151617181920212223242526272829
  1. /*
  2. * Copyright Nick Thompson, 2017
  3. * Use, modification and distribution are subject to the
  4. * Boost Software License, Version 1.0. (See accompanying file
  5. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. *
  7. * This example shows to to numerically integrate a periodic function using the adaptive_trapezoidal routine provided by boost.
  8. */
  9. #include <iostream>
  10. #include <cmath>
  11. #include <limits>
  12. #include <boost/math/quadrature/trapezoidal.hpp>
  13. int main()
  14. {
  15. using boost::math::constants::two_pi;
  16. using boost::math::constants::third;
  17. using boost::math::quadrature::trapezoidal;
  18. // This function has an analytic form for its integral over a period: 2pi/3.
  19. auto f = [](double x) { return 1/(5 - 4*cos(x)); };
  20. double Q = trapezoidal(f, (double) 0, two_pi<double>());
  21. std::cout << std::setprecision(std::numeric_limits<double>::digits10);
  22. std::cout << "The adaptive trapezoidal rule gives the integral of our function as " << Q << "\n";
  23. std::cout << "The exact result is " << two_pi<double>()*third<double>() << "\n";
  24. }