-3

I have tried looking for an example on how to find the standard deviation from a list of numbers of user input. I was wondering if someone could explain how to find the standard deviation of a list of numbers from a scanner. Any advice would be great.

-thanks in advance

JonyB
  • 3
  • 1
  • 1
  • 4
  • possible duplicate of [How do I determine the standard deviation (stddev) of a set of values?](http://stackoverflow.com/questions/895929/how-do-i-determine-the-standard-deviation-stddev-of-a-set-of-values) – Cimbali Dec 08 '14 at 22:22
  • Are you having trouble getting the numbers from user input, or the standard deviation from a list of numbers? Those are two different questions, and need to be separated here. – Teepeemm Dec 08 '14 at 22:32
  • If you are keeping a running calculation (i.e. updated each time a new number is scanned in) - take a look at the Exponentially weighted Moving Average (EWMA) formulas for standard deviation as these often have a form that is easier to update "on-line". – Rusan Kax Dec 09 '14 at 01:48
  • I was wondering how to get it from user input. And I was hoping for an explanation of how the program works, not just the code. – JonyB Dec 10 '14 at 21:01

1 Answers1

0

Sure - this will do it.

package statistics;

/**
 * Statistics
 * @author Michael
 * @link http://stackoverflow.com/questions/11978667/online-algorithm-for-calculating-standrd-deviation/11978689#11978689
 * @link http://mathworld.wolfram.com/Variance.html
 * @since 8/15/12 7:34 PM
 */
public class Statistics {

    private int n;
    private double sum;
    private double sumsq;

    public void reset() {
        this.n = 0;
        this.sum = 0.0;
        this.sumsq = 0.0;
    }

    public synchronized void addValue(double x) {
        ++this.n;
        this.sum += x;
        this.sumsq += x*x;
    }

    public synchronized double calculateMean() {
        double mean = 0.0;
        if (this.n > 0) {
            mean = this.sum/this.n;
        }
        return mean;
    }

    public synchronized double calculateVariance() {
        double variance = 0.0;
        if (this.n > 0) {
            variance = Math.sqrt(this.sumsq-this.sum*this.sum/this.n)/this.n;
        }
        return variance;
    }

    public synchronized double calculateStandardDeviation() {
        double deviation = 0.0;
        if (this.n > 1) {
            deviation = Math.sqrt((this.sumsq-this.sum*this.sum/this.n)/(this.n-1));
        }
        return deviation;
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561