Class Accumulator


  • public class Accumulator
    extends Object
    The Accumulator class is a data type for computing the running mean, sample standard deviation, and sample variance of a stream of real numbers. It provides an example of a mutable data type and a streaming algorithm.

    This implementation uses a one-pass algorithm that is less susceptible to floating-point roundoff error than the more straightforward implementation based on saving the sum of the squares of the numbers. This technique is due to B. P. Welford. Each operation takes constant time in the worst case. The amount of memory is constant - the data values are not stored.

    For additional documentation, see Section 1.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.

    Author:
    Robert Sedgewick, Kevin Wayne
    • Constructor Detail

      • Accumulator

        public Accumulator()
        Initializes an accumulator.
    • Method Detail

      • addDataValue

        public void addDataValue​(double x)
        Adds the specified data value to the accumulator.
        Parameters:
        x - the data value
      • mean

        public double mean()
        Returns the mean of the data values.
        Returns:
        the mean of the data values
      • var

        public double var()
        Returns the sample variance of the data values.
        Returns:
        the sample variance of the data values
      • stddev

        public double stddev()
        Returns the sample standard deviation of the data values.
        Returns:
        the sample standard deviation of the data values
      • count

        public int count()
        Returns the number of data values.
        Returns:
        the number of data values
      • toString

        public String toString()
        Returns a string representation of this accumulator.
        Overrides:
        toString in class Object
        Returns:
        a string representation of this accumulator
      • main

        public static void main​(String[] args)
        Unit tests the Accumulator data type. Reads in a stream of real number from standard input; adds them to the accumulator; and prints the mean, sample standard deviation, and sample variance to standard output.
        Parameters:
        args - the command-line arguments