从数字列表中找到标准偏差(用户输入)

时间:2014-12-08 21:08:08

标签: arrays math java.util.scanner standard-deviation

我试过寻找一个如何从用户输入数字列表中找到标准差的示例。我想知道是否有人可以解释如何从扫描仪中找到数字列表的标准偏差。任何建议都会很棒。

-thanks提前

1 个答案:

答案 0 :(得分:0)

当然 - 这样就可以了。

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;
    }
}