
/* 
   The class StatCalc can be used to compute several simple statistics
   for a set of numbers.  Numbers are entered into the dataset using
   the enter(double) method.  Methods are provided to return the following
   statistics for the set of numbers that have been entered:

       getCount() returns the number of numbers in the dataset.
       getMean() returns the average of the numbers
       getStandardDeviation() returns the standard deviation
       getMaximum() returns the largest number in tne dataset
       getMinimum() returns the smallest number in the dataset

   The method clear() is provided to reinitialize a dataset, so that
   a new set of numbers can be entered.

   Note:  It is illegal to call getMean(), getStandardDeviatio(),
   getMaximum(), or getMinimum() when there are no numbers in the
   dataset.  These methods throw an error if called illegally.

   David Eck, February 2, 1998

*/

public class StatCalc {

   //------------------------ public methods ---------------------------

   public void enter(double num) {  // add num to the dataset
      count++;
      sum += num;
      squareSum += num*num;
      if (count == 1) {
         min = num;
         max = num;
      } 
      else {
         if (num > max)
            max = num;
         if (num < min)
            min = num;
      }
   }

   public double getCount() {   // return number of items in dataset
      return count;
   }

   public double getMean() {    // return average of items in dataset
      if (count == 0)
         throw new ArithmeticException("Can't take the mean of zero numbers.");
      return sum / count;
   }

   public double getStandardDeviation() {  // return standard deviation of items in dataset
      if (count == 0)
         throw new ArithmeticException("Can't take the standard deviation of zero numbers.");
      double mean = getMean();
      return Math.sqrt( squareSum/count - mean*mean );
   }

   public double getMaximum() {  // return largest number in dataset
      if (count == 0)
         throw new ArithmeticException("Can't take the maximum of zero numbers.");
      return max;
   }

   public double getMinimum() {  // return smallest number in dataset
      if (count == 0)
         throw new ArithmeticException("Can't take the minimum of zero numbers.");
      return min;
   }

   public void clear() {  // reset dataset to contain zero numbers
      count = 0;
      sum = 0;
      squareSum = 0;
   }

   //------------------- private instance variables -----------------------

   private int count = 0;         // number of items entered

   private double sum = 0;        // sum of items entered
   private double squareSum = 0;  // sum of squares entered
   private double max;            // largest item entered
   private double min;            // smallest item entered


}  // end of class StatCalc