VCCC  2024.05
VisualCamp Common C++ library
stddev.hpp
Go to the documentation of this file.
1 # /*
2 # * Created by YongGyu Lee on 2020/12/08.
3 # */
4 #
5 # ifndef VCCC_NUMERIC_STDDEV_HPP
6 # define VCCC_NUMERIC_STDDEV_HPP
7 #
8 # include <cmath>
9 #
11 
12 namespace vccc {
13 
32 template<typename InputIterator, typename T,
34 inline auto
35 stddev(InputIterator first, InputIterator last, T avg)
36 {
37  return std::sqrt(
38  sum(first, last, [avg](const auto& next) { return square(next - avg); })
39  / static_cast<decay_if_float_t<T>>(std::distance(first, last)) // TODO: subtract 1
40  );
41 }
42 
51 inline auto
52 stddev(InputIterator first, InputIterator last)
53 {
54  return stddev(first, last, average(first, last));
55 }
56 
63 template<typename ...Numbers, std::enable_if_t<negation<disjunction<is_iterable<Numbers>...>>::value, int> = 0>
64 inline auto
65 stddev(Numbers... numbers)
66 {
67  return std::sqrt(
68  sum_custom([avg = average(numbers...)](auto next) { return square(next - avg); }, numbers...)
69  / static_cast<decay_if_float_t < Numbers... >> (sizeof...(Numbers))
70  );
71 }
72 
74 
80 template<typename InputIterator>
81 auto
82 avg_stddev(InputIterator first, InputIterator last)
83 {
84  auto avg = average(first, last);
85  return std::make_pair(avg, stddev(first, last, avg));
86 }
87 
89 
90 } // namespace vccc
91 
92 # endif // VCCC_NUMERIC_STDDEV_HPP
constexpr VCCC_INLINE_OR_STATIC detail::next_niebloid next
Definition: next.hpp:65
constexpr auto average(InputIterator first, InputIterator last)
get average of iterator values [first, last)
Definition: average.hpp:28
auto stddev(InputIterator first, InputIterator last, T avg)
calculate standard deviation with pre-calculated average on iterators
Definition: stddev.hpp:35
constexpr auto sum(InputIterator first, InputIterator last)
sum of iterator [first, last)
Definition: sum.hpp:57
constexpr auto sum_custom(const UnaryOperation &unary_op, const Arg &arg)
sum of variadic with custom operator
Definition: sum.hpp:99
auto avg_stddev(InputIterator first, InputIterator last)
calculate standard deviation and average
Definition: stddev.hpp:82
constexpr T square(const T &val)
get squared value
Definition: sum.hpp:116
constexpr VCCC_INLINE_OR_STATIC detail::distance_niebloid distance
Definition: distance.hpp:72
typename std::conditional_t< conjunction< std::is_same< Types, float >... >::value, float, double > decay_if_float_t
Definition: lossless_type.hpp:20
Definition: directory.h:12
constexpr VCCC_INLINE_OR_STATIC detail::element_niebloid< 0 > first
Definition: key_value.hpp:34
constexpr VCCC_INLINE_OR_STATIC detail::element_niebloid< 1 > value
Definition: key_value.hpp:35