
/**
 * Class for computing stats like mean, variance and standard deviation.
 * Written by Chris Studholme
 * Licenced for redistribution under the GNU General Public Licence
 */
public class Stats {

    /** Sum of variable.
     */
    private double sum=0;
    /** Sum of the squares of the variable.
     */
    private double sumsqr=0;
    /** Number of observations added.
     */
    private int count=0;

    /**
     * Default constructor.  Does nothing.
     */
    public Stats() {
    }

    /**
     * Add an observation.
     * @param value an observation
     */
    public void add(double value) {
	sum+=value;
	sumsqr+=value*value;
	++count;
    }

    /**
     * Return count of observations.
     * @return count value
     */
    public int getCount() {
	return count;
    }

    /**
     * Return sum of observations added.
     * @return sum
     */
    public double getSum() {
	return sum;
    }

    /**
     * Compute mean of observations.  
     * @return mean value
     */
    public double getMean() {
	return sum/count;
    }
    
    /**
     * Compute variance of observations.
     * @return variance
     */
    public double getVariance() {
	double var = (sumsqr-sum*sum/count)/count;
	return (var>0 ? var : 0);
    }

    /**
     * Compute standard deviation of observations.
     * @return standard deviation
     */
    public double getStandardDeviation() {
	return Math.sqrt(getVariance());
    }
}
