OnePass.java


Below is the syntax highlighted version of OnePass.java from §9.7 Optimization.



/******************************************************************************
 *  Compilation:  javac OnePass.java
 *  Execution:    java Average < data.txt
 *  Dependencies: StdIn.java
 *  
 *  Reads in a sequence of real numbers, and computes their average
 *  and standard deviation using one-pass formula.
 *
 *  Limitations
 *  -----------
 *   -  Not numerically stable.
 *
 *  % java OnePass
 *  10.0 5.0 6.0
 *  3.0 7.0 32.0
 *  <Ctrl-d>
 *  Number  = 6
 *  Average = 10.5
 *  Standard deviation = 10.784247771634329

 * 
 *  % java OnePass
 *  1000000000 1000000001 1000000002
 *  <Ctrl-d>
 *  Number  = 3
 *  Average = 1.000000001E9
 *  Standard deviation = 0.0            // correct answer = 1.0
 *
 *  % java OnePass
 *  0.5000000000000002 0.5000000000000001
 *  Number  = 2
 *  Average = 0.5000000000000002
 *  Standard deviation = NaN            // variance is negative!!!
 *
 *  Note <Ctrl-d> signifies the end of file on Unix.
 *  On windows use <Ctrl-z>.
 *
 ******************************************************************************/

public class OnePass { 
   public static void main(String[] args) { 
      int n = 0;           // number input values
      double sum  = 0.0;   // sum of input values
      double sum2 = 0.0;   // sum of squares of input values

      // read data and compute statistics
      while(!StdIn.isEmpty()) {
         double x = StdIn.readDouble();
         n++;
         sum += x;
         sum2 += x*x;
      }

      double avg = sum / n;
      double variance = (n*sum2 - sum*sum) / (n*(n-1));
      double stddev = Math.sqrt(variance);
      StdOut.println("Number  = " + n);
      StdOut.println("Average = " + avg);
      StdOut.println("Standard deviation = " + stddev);
   }
}


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