/thirdparty/liblastfm2/src/fingerprint/fplib/FloatingAverage.h

http://github.com/tomahawk-player/tomahawk · C Header · 106 lines · 73 code · 13 blank · 20 comment · 6 complexity · f4cc2a49564ef94d0ef0706282c8a44d MD5 · raw file

  1. /*
  2. Copyright 2005-2009 Last.fm Ltd. <mir@last.fm>
  3. This file is part of liblastfm.
  4. liblastfm is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. liblastfm is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with liblastfm. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #ifndef __FLOAT_AVERAGE_H__
  16. #define __FLOAT_AVERAGE_H__
  17. //#include <deque>
  18. #include <limits>
  19. #include "CircularArray.h"
  20. template <typename T>
  21. class FloatingAverage
  22. {
  23. public:
  24. FloatingAverage(size_t size)
  25. {
  26. m_values.resize(size);
  27. m_valIt = m_values.head();
  28. m_sum = 0;
  29. m_bufferFilled = false;
  30. }
  31. void purge()
  32. {
  33. m_sum = 0;
  34. const T* pCircularBuffer = m_values.get_buffer();
  35. const int size = m_values.size();
  36. for ( int i = 0; i < size; ++i )
  37. m_sum += pCircularBuffer[i];
  38. }
  39. void add(const T& value)
  40. {
  41. m_sum += value;
  42. if ( m_bufferFilled )
  43. {
  44. m_sum -= *m_valIt;
  45. *m_valIt = value;
  46. ++m_valIt;
  47. }
  48. else
  49. {
  50. *m_valIt = value;
  51. ++m_valIt;
  52. if ( m_valIt == m_values.head() )
  53. m_bufferFilled = true;
  54. }
  55. }
  56. T getAverage() const
  57. {
  58. if ( !m_bufferFilled )
  59. return m_sum / (m_valIt - m_values.head());
  60. else
  61. return m_sum / m_values.size();
  62. }
  63. T getError() const
  64. {
  65. T real_sum = 0;
  66. const T* pCircularBuffer = m_values.get_buffer();
  67. for ( int i = 0; i < size; ++i )
  68. real_sum += pCircularBuffer[i];
  69. return abs(real_sum - m_sum) / this->size();
  70. }
  71. size_t size() const
  72. {
  73. return m_values.size();
  74. }
  75. void clear()
  76. {
  77. m_bufferFilled = false;
  78. m_values.zero_fill();
  79. m_valIt = m_values.head();
  80. m_sum = 0;
  81. }
  82. private:
  83. //std::deque<T> m_values;
  84. CircularArray<T> m_values;
  85. typename CircularArray<T>::iterator m_valIt;
  86. bool m_bufferFilled;
  87. T m_sum;
  88. };
  89. #endif // __FLOAT_AVERAGE_H__