Calculate rolling / moving average in C++

前端 未结 10 2101
攒了一身酷
攒了一身酷 2020-12-02 08:09

I know this is achievable with boost as per:

Using boost::accumulators, how can I reset a rolling window size, does it keep extra history?

But I really would

10条回答
  •  天命终不由人
    2020-12-02 08:50

    a simple moving average for 10 items, using a list:

    #include 
    
    std::list listDeltaMA;
    
    float getDeltaMovingAverage(float delta)
    {
        listDeltaMA.push_back(delta);
        if (listDeltaMA.size() > 10) listDeltaMA.pop_front();
        float sum = 0;
        for (std::list::iterator p = listDeltaMA.begin(); p != listDeltaMA.end(); ++p)
            sum += (float)*p;
        return sum / listDeltaMA.size();
    }
    

提交回复
热议问题