Input/Output: StdIn and StdOut for Filtering Data – stat

Assignment:
Extend program Stats.java shown below to create a filter that prints all the values that are further than 1.5 standard deviations from the mean. FilterStats_YI.java

Stats.java takes an integer N from the command line, reads N double values from standard input, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by N – 1).

[spoiler title=’Stats.java’]

Below is the syntax highlighted version of Stats.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac Stats.java
 *  Execution:    java Stats n
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  Reads in a command-line integer n, a sequence of n real numbers from
 *  standard input, and prints the mean and sample standard deviation.
 *
 *  % java Stats 6
 *  10.0 5.0 6.0
 *  3.0 7.0 32.0
 *  
 *  Mean                      = 10.5
 *  Sample standard deviation = 10.784247771634329
 *
 *  Note  signifies the end of file on Unix.
 *  On windows use .
 *
 ******************************************************************************/

public class Stats { 
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        double[] a = new double[n];

        // read data and compute statistics
        for (int i = 0; i < n; i++) {
            a[i] = StdIn.readDouble();
        }

        // compute mean
        double sum = 0.0;
        for (int i = 0; i < n; i++) {
            sum += a[i];
        }
        double mean = sum / n;

        // compute standard deviation
        double sum2 = 0.0;
        for (int i = 0; i < n; i++) {
            sum2 += (a[i] - mean) * (a[i] - mean);
        }
        double stddev = Math.sqrt(sum2 / (n - 1));

        // print results
        StdOut.println("Mean                      = " + mean);
        StdOut.println("Sample standard deviation = " + stddev);
    }
}

Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. Last updated: Fri Oct 20 14:12:12 EDT 2017. [/spoiler]