Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

43
LINES

< > BotCompany Repo | #1019129 // RollingAverage (compact version with double[] array)

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (1793L/12K).

sclass RollingAverage {
  int windowSize = 50;
  int recalcEvery = 1000; // to counter floating point errors
  
  int nRecalc;
  double sum;
  double[] list;
  int start, len;
  
  *() {}
  *(int *windowSize) {}
  
  synchronized void add(double d) {
    init();
    
    if (++nRecalc >= recalcEvery) {
      nRecalc = 0;
      sum = 0;
      for i to len: sum += _get(i);
    }
    
    if (len == windowSize) {
      sum -= _get(0);
      len--;
      start = (start+1) % windowSize;
    }
      
    list[(start+len) % windowSize] = d;
    ++len;
    sum += d;
  }
  
  double _get(int i) { ret list[(start+i) % windowSize]; }
  
  synchronized double get() {
    init();
    ret doubleRatio(sum, len);
  }
  
  void init {
    if (list == null) list = new double[windowSize];
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 12 computer(s): bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1019129
Snippet name: RollingAverage (compact version with double[] array)
Eternal ID of this version: #1019129/7
Text MD5: 8410ead4660b056bd683ce676ac4160a
Transpilation MD5: cefdbbc366a7439b93f6fc4b3b441b8f
Author: stefan
Category: javax / maths
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-08-18 11:32:06
Source code size: 828 bytes / 43 lines
Pitched / IR pitched: No / No
Views / Downloads: 477 / 1052
Version history: 6 change(s)
Referenced in: #1024553 - RollingAverage (memory-hungry version with LinkedList)
#1029191 - Average
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)