stats.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 <boost/config/no_tr1/cmath.hpp>
  11. #include <boost/cstdint.hpp>
  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. m_count(0)
  24. {}
  25. void add(const T& val)
  26. {
  27. if(val < m_min)
  28. m_min = val;
  29. if(val > m_max)
  30. m_max = val;
  31. m_total += val;
  32. ++m_count;
  33. m_squared_total += val*val;
  34. }
  35. T min BOOST_PREVENT_MACRO_SUBSTITUTION()const{ return m_min; }
  36. T max BOOST_PREVENT_MACRO_SUBSTITUTION()const{ return m_max; }
  37. T total()const{ return m_total; }
  38. T mean()const{ return m_total / static_cast<T>(m_count); }
  39. boost::uintmax_t count()const{ return m_count; }
  40. T variance()const
  41. {
  42. BOOST_MATH_STD_USING
  43. T t = m_squared_total - m_total * m_total / m_count;
  44. t /= m_count;
  45. return t;
  46. }
  47. T variance1()const
  48. {
  49. BOOST_MATH_STD_USING
  50. T t = m_squared_total - m_total * m_total / m_count;
  51. t /= (m_count-1);
  52. return t;
  53. }
  54. T rms()const
  55. {
  56. BOOST_MATH_STD_USING
  57. return sqrt(m_squared_total / static_cast<T>(m_count));
  58. }
  59. stats& operator+=(const stats& s)
  60. {
  61. if(s.m_min < m_min)
  62. m_min = s.m_min;
  63. if(s.m_max > m_max)
  64. m_max = s.m_max;
  65. m_total += s.m_total;
  66. m_squared_total += s.m_squared_total;
  67. m_count += s.m_count;
  68. return *this;
  69. }
  70. private:
  71. T m_min, m_max, m_total, m_squared_total;
  72. boost::uintmax_t m_count;
  73. };
  74. } // namespace tools
  75. } // namespace math
  76. } // namespace boost
  77. #endif