Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Mar 22nd, 2012  |  syntax: Java  |  size: 0.62 KB  |  views: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. private static class RunningAvg {
  2.       private final long[] slots;
  3.       private int          offset;
  4.       private long         sum;
  5.  
  6.       public RunningAvg(int slotCount) {
  7.          this.slots = new long[slotCount];
  8.          this.offset = 0;
  9.       }
  10.  
  11.       public void add(long value) {
  12.           // add new value and remove old value (last in array) from sum
  13.           sum = value - slots[(offset+1) % slots.length];
  14.           slots[offset++ % slots.length] = value;
  15.       }
  16.  
  17.       public long avg() {
  18.          int sampleCount = Math.min(this.offset, this.slots.length);
  19.          return sum / sampleCount;
  20.       }
  21.    }
clone this paste RAW Paste Data