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).

1  
sclass RollingAverage {
2  
  int windowSize = 50;
3  
  int recalcEvery = 1000; // to counter floating point errors
4  
  
5  
  int nRecalc;
6  
  double sum;
7  
  double[] list;
8  
  int start, len;
9  
  
10  
  *() {}
11  
  *(int *windowSize) {}
12  
  
13  
  synchronized void add(double d) {
14  
    init();
15  
    
16  
    if (++nRecalc >= recalcEvery) {
17  
      nRecalc = 0;
18  
      sum = 0;
19  
      for i to len: sum += _get(i);
20  
    }
21  
    
22  
    if (len == windowSize) {
23  
      sum -= _get(0);
24  
      len--;
25  
      start = (start+1) % windowSize;
26  
    }
27  
      
28  
    list[(start+len) % windowSize] = d;
29  
    ++len;
30  
    sum += d;
31  
  }
32  
  
33  
  double _get(int i) { ret list[(start+i) % windowSize]; }
34  
  
35  
  synchronized double get() {
36  
    init();
37  
    ret doubleRatio(sum, len);
38  
  }
39  
  
40  
  void init {
41  
    if (list == null) list = new double[windowSize];
42  
  }
43  
}

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: 478 / 1053
Version history: 6 change(s)
Referenced in: [show references]