1 /* 2 * Copyright 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package tests.util; 18 19 public class SummaryStatistics { 20 /** The number of values seen. */ 21 private int numValues; 22 23 /** Sum of the values. */ 24 private double sum; 25 26 /** Sum of the squares of the values added. */ 27 private double squaresSum; 28 29 /** The previously added value. */ 30 private double lastValue; 31 32 public SummaryStatistics() { 33 } 34 35 private double square(double value) { 36 return value * value; 37 } 38 39 /** Add a new value to the values seen. */ 40 public void add(double value) { 41 sum += value - lastValue; 42 squaresSum += square(value) - square(lastValue); 43 numValues++; 44 lastValue = value; 45 } 46 47 /** Mean of the values seen. */ 48 public double mean() { 49 return sum / numValues; 50 } 51 52 /** Variance of the values seen. */ 53 public double var() { 54 return (squaresSum / numValues) - square(mean()); 55 } 56 57 /** Standard deviation of the values seen. */ 58 public double stddev() { 59 return Math.sqrt(var()); 60 } 61 62 /** Coefficient of variation of the values seen. */ 63 public double coeffVar() { 64 return stddev() / mean(); 65 } 66 67 public String toString() { 68 StringBuilder sb = new StringBuilder("SummaryStatistics{"); 69 sb.append("n="); 70 sb.append(numValues); 71 sb.append(",mean="); 72 sb.append(mean()); 73 sb.append(",var="); 74 sb.append(var()); 75 sb.append(",stddev="); 76 sb.append(stddev()); 77 sb.append(",coeffVar="); 78 sb.append(coeffVar()); 79 sb.append('}'); 80 return sb.toString(); 81 } 82 } 83