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 /**
13 * Simple double statistics, computed incrementally, variance and standard
14 * deviation using Welford's online algorithm, see
15 * https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
16 *
17 * @since 5.1.9
18 */
19 public class Stats {
20 private int n = 0;
21
22 private double avg = 0.0;
23
24 private double min = 0.0;
25
26 private double max = 0.0;
27
28 private double sum = 0.0;
29
30 /**
31 * Add a value
32 *
33 * @param x
34 * value
35 */
36 public void add(double x) {
37 n++;
38 min = n == 1 ? x : Math.min(min, x);
39 max = n == 1 ? x : Math.max(max, x);
40 double d = x - avg;
41 avg += d / n;
42 sum += d * d * (n - 1) / n;
43 }
44
45 /**
46 * @return number of the added values
47 */
48 public int count() {
49 return n;
50 }
51
52 /**
53 * @return minimum of the added values
54 */
55 public double min() {
56 if (n < 1) {
57 return Double.NaN;
58 }
59 return min;
60 }
61
62 /**
63 * @return maximum of the added values
64 */
65 public double max() {
66 if (n < 1) {
67 return Double.NaN;
68 }
69 return max;
70 }
71
72 /**
73 * @return average of the added values
74 */
75
76 public double avg() {
77 if (n < 1) {
78 return Double.NaN;
79 }
80 return avg;
81 }
82
83 /**
84 * @return variance of the added values
85 */
86 public double var() {
87 if (n < 2) {
88 return Double.NaN;
89 }
90 return sum / (n - 1);
91 }
92
93 /**
94 * @return standard deviation of the added values
95 */
96 public double stddev() {
97 return Math.sqrt(this.var());
98 }
99 }