💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef ANTKEEPER_MATH_QUADRATURE_HPP
  20. #define ANTKEEPER_MATH_QUADRATURE_HPP
  21. #include <iterator>
  22. #include <type_traits>
  23. namespace math {
  24. /// Numerical integration functions.
  25. namespace quadrature {
  26. /**
  27. * Approximates the definite integral of a function using the trapezoidal rule.
  28. *
  29. * @param f Unary function object to integrate.
  30. * @param first,last Range of sample points on `[first, last)`.
  31. * @return Approximated integral of @p f.
  32. *
  33. * @see https://en.wikipedia.org/wiki/Trapezoidal_rule
  34. */
  35. template<class UnaryOp, class InputIt>
  36. typename std::invoke_result<UnaryOp, typename std::iterator_traits<InputIt>::value_type>::type trapezoid(UnaryOp f, InputIt first, InputIt last)
  37. {
  38. typedef typename std::invoke_result<UnaryOp, typename std::iterator_traits<InputIt>::value_type>::type result_type;
  39. if (first == last)
  40. return result_type(0);
  41. result_type f_a = f(*first);
  42. InputIt second = first;
  43. ++second;
  44. if (second == last)
  45. return f_a;
  46. result_type f_b = f(*second);
  47. result_type sum = (f_a + f_b) / result_type(2) * (*second - *first);
  48. for (first = second++; second != last; first = second++)
  49. {
  50. f_a = f_b;
  51. f_b = f(*second);
  52. sum += (f_a + f_b) / result_type(2) * (*second - *first);
  53. }
  54. return sum;
  55. }
  56. } // namespace quadrature
  57. } // namespace math
  58. #endif // ANTKEEPER_MATH_QUADRATURE_HPP