Calculate rolling / moving average in C++

前端 未结 10 2111
攒了一身酷
攒了一身酷 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:56

    I use this quite often in hard realtime systems that have fairly insane update rates (50kilosamples/sec) As a result I typically precompute the scalars.

    To compute a moving average of N samples: scalar1 = 1/N; scalar2 = 1 - scalar1; // or (1 - 1/N) then:

    Average = currentSample*scalar1 + Average*scalar2;

    Example: Sliding average of 10 elements

    double scalar1 = 1.0/10.0;  // 0.1
    double scalar2 = 1.0 - scalar1; // 0.9
    bool first_sample = true;
    double average=0.0;
    while(someCondition)
    {
       double newSample = getSample();
       if(first_sample)
       {
        // everybody forgets the initial condition *sigh*
          average = newSample;
          first_sample = false;
       }
       else
       {
          average = (sample*scalar1) + (average*scalar2);
       }
     }
    

    Note: this is just a practical implementation of the answer given by steveha above. Sometimes it's easier to understand a concrete example.

提交回复
热议问题