Calculating moving average in C++

后端 未结 4 755
情深已故
情深已故 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:13

    #include 
    #include 
    
    // Sample - the type of a single sample
    // Date - the type of a time notation
    // DateDiff - the type of difference of two Dates    
    template 
    class TWMA {
    private:
      typedef std::map qType;
      const DateDiff windowSize; // The time width of the sampling window
      qType samples; // A set of sample/date pairs
      Sample average; // The answer
    
    public:
    
      // windowSize - The time width of the sampling window
      TWMA(const DateDiff& windowSize) : windowSize(windowSize), average(0) {}
    
      // Call this each time you receive a sample
      void
      Update(const Sample& sample, const Date& now) {
        // First throw away all old data
        Date then(now - windowSize);
        samples.erase(samples.begin(), samples.upper_bound(then));
    
        // Next add new data
        samples[now] = sample;
    
        // Compute average: note: this could move to Average(), depending upon
        // precise user requirements.
        Sample sum = Sample();
        for(typename qType::iterator it = samples.begin();
            it != samples.end();
            ++it) {
          DateDiff duration(it->first - then);
          sum += duration * it->second;
          then = it->first;
        }
        average = sum / windowSize;
      }
    
      // Call this when you need the answer.
      const Sample& Average() { return average; }
    
    };
    
    int main () {
      TWMA samples(10);
    
      samples.Update(1, 1);
      std::cout << samples.Average() << "\n"; // 1
      samples.Update(1, 2);
      std::cout << samples.Average() << "\n"; // 1
      samples.Update(1, 3);
      std::cout << samples.Average() << "\n"; // 1
      samples.Update(10, 20);
      std::cout << samples.Average() << "\n"; // 10
      samples.Update(0, 25);
      std::cout << samples.Average() << "\n"; // 5
      samples.Update(0, 30);
      std::cout << samples.Average() << "\n"; // 0
    }
    

提交回复
热议问题