20 #ifndef ANTKEEPER_MATH_QUADRATURE_HPP
21 #define ANTKEEPER_MATH_QUADRATURE_HPP
24 #include <type_traits>
29 namespace quadrature {
41 template<
class UnaryOp,
class InputIt>
42 [[nodiscard]]
typename std::invoke_result<UnaryOp, typename std::iterator_traits<InputIt>::value_type>::type
43 simpson(UnaryOp f, InputIt first, InputIt last)
45 typedef typename std::iterator_traits<InputIt>::value_type input_type;
46 typedef typename std::invoke_result<UnaryOp, input_type>::type output_type;
47 typedef decltype(*last - *first) difference_type;
50 return output_type{0};
52 output_type f_a = f(*first);
54 InputIt second = first;
60 difference_type h = *second - *first;
61 output_type f_b = f(*first + h / difference_type(2));
62 output_type f_c = f(*second);
64 output_type
sum = (f_a + f_b * difference_type(4) + f_c) * h;
66 for (first = second++; second != last; first = second++)
72 f_b = f(*first + h / difference_type(2));
74 sum += (f_a + f_b * difference_type(4) + f_c) * h;
77 return sum / difference_type(6);
90 template<
class UnaryOp,
class InputIt>
91 [[nodiscard]]
typename std::invoke_result<UnaryOp, typename std::iterator_traits<InputIt>::value_type>::type
94 typedef typename std::iterator_traits<InputIt>::value_type input_type;
95 typedef typename std::invoke_result<UnaryOp, input_type>::type output_type;
96 typedef decltype(*last - *first) difference_type;
99 return output_type{0};
101 output_type f_a = f(*first);
103 InputIt second = first;
109 output_type f_b = f(*second);
110 output_type
sum = (f_a + f_b) * (*second - *first);
112 for (first = second++; second != last; first = second++)
116 sum += (f_a + f_b) * (*second - *first);
119 return sum / difference_type(2);
std::invoke_result< UnaryOp, typename std::iterator_traits< InputIt >::value_type >::type simpson(UnaryOp f, InputIt first, InputIt last)
Approximates the definite integral of a function using Simpson's 1/3 rule.
std::invoke_result< UnaryOp, typename std::iterator_traits< InputIt >::value_type >::type trapezoid(UnaryOp f, InputIt first, InputIt last)
Approximates the definite integral of a function using the trapezoidal rule.
Mathematical functions and data types.
constexpr T sum(const vector< T, N > &x) noexcept
Calculates the sum of all elements in a vector.