001package algs13; 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac Stats.java 005 * Execution: java Stats < input.txt 006 * Dependencies: Bag.java StdIn.java StdOut.java 007 * 008 * Reads in a sequence of real numbers from standard input and 009 * computes their mean and standard deviation. 010 * 011 * % java Stats 012 * 100 99 101 120 98 107 109 81 101 90 013 * Mean: 100.60 014 * Std dev: 10.51 015 * 016 *************************************************************************/ 017 018public class XStats { 019 public static void main(String[] args) { 020 021 // read in numbers 022 Bag<Double> numbers = new Bag<>(); 023 while (!StdIn.isEmpty()) { 024 numbers.add(StdIn.readDouble()); 025 } 026 int N = numbers.size(); 027 028 // compute mean 029 double sum = 0.0; 030 for (double x : numbers) 031 sum += x; 032 double mean = sum/N; 033 034 // compute standard deviation 035 sum = 0.0; 036 for (double x : numbers) { 037 sum += (x - mean) * (x - mean); 038 } 039 double std = Math.sqrt(sum/(N-1)); 040 041 StdOut.format("Mean: %.2f\n", mean); 042 StdOut.format("Std dev: %.2f\n", std); 043 } 044}