stats.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // (C) Copyright John Maddock 2005-2006.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_MATH_TOOLS_STATS_INCLUDED
  6. #define BOOST_MATH_TOOLS_STATS_INCLUDED
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #endif
  10. #include <cstdint>
  11. #include <cmath>
  12. #include <boost/math/tools/precision.hpp>
  13. namespace boost{ namespace math{ namespace tools{
  14. template <class T>
  15. class stats
  16. {
  17. public:
  18. stats()
  19. : m_min(tools::max_value<T>()),
  20. m_max(-tools::max_value<T>()),
  21. m_total(0),
  22. m_squared_total(0)
  23. {}
  24. void add(const T& val)
  25. {
  26. if(val < m_min)
  27. m_min = val;
  28. if(val > m_max)
  29. m_max = val;
  30. m_total += val;
  31. ++m_count;
  32. m_squared_total += val*val;
  33. }
  34. T min BOOST_MATH_PREVENT_MACRO_SUBSTITUTION()const{ return m_min; }
  35. T max BOOST_MATH_PREVENT_MACRO_SUBSTITUTION()const{ return m_max; }
  36. T total()const{ return m_total; }
  37. T mean()const{ return m_total / static_cast<T>(m_count); }
  38. std::uintmax_t count()const{ return m_count; }
  39. T variance()const
  40. {
  41. BOOST_MATH_STD_USING
  42. T t = m_squared_total - m_total * m_total / m_count;
  43. t /= m_count;
  44. return t;
  45. }
  46. T variance1()const
  47. {
  48. BOOST_MATH_STD_USING
  49. T t = m_squared_total - m_total * m_total / m_count;
  50. t /= (m_count-1);
  51. return t;
  52. }
  53. T rms()const
  54. {
  55. BOOST_MATH_STD_USING
  56. return sqrt(m_squared_total / static_cast<T>(m_count));
  57. }
  58. stats& operator+=(const stats& s)
  59. {
  60. if(s.m_min < m_min)
  61. m_min = s.m_min;
  62. if(s.m_max > m_max)
  63. m_max = s.m_max;
  64. m_total += s.m_total;
  65. m_squared_total += s.m_squared_total;
  66. m_count += s.m_count;
  67. return *this;
  68. }
  69. private:
  70. T m_min, m_max, m_total, m_squared_total;
  71. std::uintmax_t m_count{0};
  72. };
  73. } // namespace tools
  74. } // namespace math
  75. } // namespace boost
  76. #endif