Skip to content

Instantly share code, notes, and snippets.

@stanio
Last active October 11, 2020 13:43
Show Gist options
  • Save stanio/d753c45208762b8833b5db94b830e874 to your computer and use it in GitHub Desktop.
Save stanio/d753c45208762b8833b5db94b830e874 to your computer and use it in GitHub Desktop.
Calculating the average incrementally
//package ;
/**
* @see <a href="https://ubuntuincident.wordpress.com/2012/04/25/calculating-the-average-incrementally/">Calculating the average incrementally</a>
*/
public class Avg {
private double value = Double.NaN;
private long count;
public Avg() {
// no-args
}
public double value() {
return value;
}
public long count() {
return count;
}
public void add(double number) {
if (count++ == 0) {
value = number;
} else {
value += (number - value) / count;
}
}
public void reset() {
value = Double.NaN;
count = 0;
}
public static double calc(int[] numbers) {
if (numbers.length == 0) {
return Double.NaN;
}
double avg = numbers[0];
for (int i = 1, len = numbers.length; i < len; i++) {
avg += (numbers[i] - avg) / (i + 1);
}
return avg;
}
public static void main(String[] args) {
int[] numbers = { 5, -3, 7 };
System.out.println(Avg.calc(numbers));
Avg avg = new Avg();
for (int i = 0; i < numbers.length; i++) {
avg.add(numbers[i]);
}
System.out.println(avg.value());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment