Calculating moving average in C++

后端 未结 4 765
情深已故
情深已故 2021-02-05 15:43

I am trying to calculate the moving average of a signal. The signal value ( a double ) is updated at random times. I am looking for an efficient way to calculate it\'s time wei

4条回答
  •  情深已故
    2021-02-05 16:12

    Note: Apparently this is not the way to approach this. Leaving it here for reference on what is wrong with this approach. Check the comments.

    UPDATED - based on Oli's comment... not sure about the instability that he is talking about though.

    Use a sorted map of "arrival times" against values. Upon arrival of a value add the arrival time to the sorted map along with it's value and update the moving average.

    warning this is pseudo-code:

    SortedMapType< int, double > timeValueMap;
    
    void onArrival(double value)
    {
        timeValueMap.insert( (int)time(NULL), value);
    }
    
    //for example this runs every 10 seconds and the moving window is 120 seconds long
    void recalcRunningAverage()
    {
        // you know that the oldest thing in the list is 
        // going to be 129.9999 seconds old
        int expireTime = (int)time(NULL) - 120;
        int removeFromTotal = 0;
        MapIterType i;
        for( i = timeValueMap.begin();
        (i->first < expireTime || i != end) ; ++i )
        {
        }
    
        // NOW REMOVE PAIRS TO LEFT OF i
    
        // Below needs to apply your time-weighting to the remaining values
        runningTotal = calculateRunningTotal(timeValueMap); 
        average = runningTotal/timeValueMap.size();
    }
    

    There... Not fully fleshed out but you get the idea.

    Things to note: As I said the above is pseudo code. You'll need to choose an appropriate map. Don't remove the pairs as you iterate through as you will invalidate the iterator and will have to start again.
    See Oli's comment below also.

提交回复
热议问题