DryChem 1.0.0
A generic, compile-time C++ toolbox with no dependencies for the modern computational chemistry project.
Loading...
Searching...
No Matches
statistics.hpp
Go to the documentation of this file.
1// Copyright (c) 2020-2025 Cody R. Drisko. All rights reserved.
2// Licensed under the MIT License. See the LICENSE file in the project root for more information.
3//
4// Name: statistics.hpp
5// Author: cdrisko
6// Date: 02/03/2020-08:22:29
7// Description: Common mathematical functions relating to statistics
8
9#ifndef DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_MATH_STATISTICS_STATISTICS_HPP
10#define DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_MATH_STATISTICS_STATISTICS_HPP
11
12#include <cmath>
13#include <cstddef>
14#include <iterator>
15#include <numeric>
16#include <type_traits>
17#include <utility>
18
19namespace CppUtils::Math
20{
28 template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
29 constexpr int findOrderOfMagnitude(T value) noexcept
30 {
31 return static_cast<int>(std::floor(std::log10(value)));
32 }
33
34
44 template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
45 constexpr long double findAbsoluteError(T expectedValue, std::size_t significantFigures) noexcept
46 {
47 return std::pow(10, findOrderOfMagnitude(expectedValue) - (significantFigures - 1));
48 }
49
50
60 template<typename Iterator, typename T = typename std::iterator_traits<Iterator>::value_type,
61 typename = std::enable_if_t<std::is_default_constructible_v<T>>>
62 constexpr T calculateAverage(Iterator x_begin, Iterator x_end)
63 {
64 T init {};
65 T result {std::accumulate(x_begin, x_end, init) / (x_end - x_begin)};
66
67 return result;
68 }
69
70
82 template<typename Iterator, typename T = typename std::iterator_traits<Iterator>::value_type,
83 typename = std::enable_if_t<std::is_default_constructible_v<T>>>
84 constexpr decltype(auto) calculateVariance(Iterator x_begin, Iterator x_end)
85 {
86 using Txx = decltype(*x_begin * *x_begin);
87
88 std::ptrdiff_t x_size {x_end - x_begin};
89
90 T average {calculateAverage(x_begin, x_end)};
91
92 Txx init {};
93 Txx result = std::accumulate(x_begin, x_end, init,
94 [&average](Txx res, T x) { return std::move(res) + ((x - average) * (x - average)); }) / (x_size - 1);
95
96 return result;
97 }
98} // namespace CppUtils::Math
99
100#endif
Definition backwardsDifferenceMethod.hpp:20
constexpr T calculateAverage(Iterator x_begin, Iterator x_end)
Definition statistics.hpp:62
constexpr long double findAbsoluteError(T expectedValue, std::size_t significantFigures) noexcept
Definition statistics.hpp:45
constexpr decltype(auto) calculateVariance(Iterator x_begin, Iterator x_end)
Definition statistics.hpp:84
constexpr int findOrderOfMagnitude(T value) noexcept
Definition statistics.hpp:29