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