コード例 #1
0
        /* This function calculates the average of values in cBuf */
        void updateAverage( INTYPE data)
        {
            double tempVal = 0;
            float mulFactor = 0;
            INTYPE oldElement = 0;

            if( !stableStream )
            {
                /* Add data to Buffer */
                cBuf.push_back(data);
                mulFactor = 1/(double)(cBuf.size());

                /* If number of elements in the buffer < total buffer capacity
                 * Calculate the average using loops */

                for(int i = 0; i < (int)cBuf.size(); i++)
                {
                    tempVal += cBuf[i];
                }

                tempVal = tempVal * mulFactor;

                currentAverage = tempVal;

                stableStream = (cBuf.size() == cBuf.capacity());
            }
            else
            {
                /* Efficient way of calculating average in case the buffer is full
                 * Every calculation will update the current average value.
                 * To get new average:
                 * new_average =
                 *         current_average +
                 *         ( new_element - oldest_element ) * mulFactor
                 *
                 * The CircularBuffer at this point is Full
                 * */

                oldElement = cBuf.peek_front();
                /* Adding new data Element */

                cBuf.push_back(data, OVERWRITE_OLD_DATA);

                /* We now have a pointer to the old element in the buffer */
                tempVal = currentAverage;

                tempVal = tempVal + ( (  data - oldElement ) / ( cBuf.capacity() ) );

                currentAverage = tempVal;

            }

        }