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

31
LINES

< > BotCompany Repo | #1036458 // HalfWelford [running average - I think this is nonsense. Average does the same]

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

Transpiled version (10102L) is out of date.

// from https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
srecord HalfWelford(long count, dbl mean) {
  void add(double newValue) {
    count++;
    dbl delta = newValue - mean;
    mean += delta / count;
  }
  
  void remove(double valueToRemove) {
    guarantee(count > 0);
    
    double newValue = valueToRemove;
    mean = (mean-newValue/count)/(1-1.0/count);
    --count;
  }
 
  bool isEmpty() { ret count == 0; }

  dbl average aka avg aka mean() { ret count == 0 ? Double.NaN : mean; }

  toString {
    S s = nValues(count);
    if (!isEmpty())
      s += ", avg: " + avg();
    ret s;
  }
  
  double get() {
    ret avg();
  }
}

Author comment

Began life as a copy of #1033575

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1036458
Snippet name: HalfWelford [running average - I think this is nonsense. Average does the same]
Eternal ID of this version: #1036458/2
Text MD5: bf9d391c493cbf9ba320dab793c8dbca
Author: stefan
Category: javax / maths
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-12-16 02:00:18
Source code size: 714 bytes / 31 lines
Pitched / IR pitched: No / No
Views / Downloads: 137 / 196
Version history: 1 change(s)
Referenced in: [show references]