Stats.java

  1. /*
  2.  * Copyright (C) 2019, Matthias Sohn <matthias.sohn@sap.com> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.util;

  11. /**
  12.  * Simple double statistics, computed incrementally, variance and standard
  13.  * deviation using Welford's online algorithm, see
  14.  * https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
  15.  *
  16.  * @since 5.1.9
  17.  */
  18. public class Stats {
  19.     private int n = 0;

  20.     private double avg = 0.0;

  21.     private double min = 0.0;

  22.     private double max = 0.0;

  23.     private double sum = 0.0;

  24.     /**
  25.      * Add a value
  26.      *
  27.      * @param x
  28.      *            value
  29.      */
  30.     public void add(double x) {
  31.         n++;
  32.         min = n == 1 ? x : Math.min(min, x);
  33.         max = n == 1 ? x : Math.max(max, x);
  34.         double d = x - avg;
  35.         avg += d / n;
  36.         sum += d * d * (n - 1) / n;
  37.     }

  38.     /**
  39.      * @return number of the added values
  40.      */
  41.     public int count() {
  42.         return n;
  43.     }

  44.     /**
  45.      * @return minimum of the added values
  46.      */
  47.     public double min() {
  48.         if (n < 1) {
  49.             return Double.NaN;
  50.         }
  51.         return min;
  52.     }

  53.     /**
  54.      * @return maximum of the added values
  55.      */
  56.     public double max() {
  57.         if (n < 1) {
  58.             return Double.NaN;
  59.         }
  60.         return max;
  61.     }

  62.     /**
  63.      * @return average of the added values
  64.      */

  65.     public double avg() {
  66.         if (n < 1) {
  67.             return Double.NaN;
  68.         }
  69.         return avg;
  70.     }

  71.     /**
  72.      * @return variance of the added values
  73.      */
  74.     public double var() {
  75.         if (n < 2) {
  76.             return Double.NaN;
  77.         }
  78.         return sum / (n - 1);
  79.     }

  80.     /**
  81.      * @return standard deviation of the added values
  82.      */
  83.     public double stddev() {
  84.         return Math.sqrt(this.var());
  85.     }
  86. }