如何计算C ++或Java中的方差,中位数和标准差?

时间:2011-11-02 23:15:31

标签: java c++ math

  

可能重复:
  Simple statistics - Java packages for calculating mean, standard deviation, etc

我有一些双打的矢量(1.1,2,3,5)。如何计算方差,中位数和标准差?

Java或C ++甚至伪代码都可以。

2 个答案:

答案 0 :(得分:109)

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

答案 1 :(得分:0)

要计算平均值,请遍历列表/数组,跟踪部分总和和长度。然后返回sum/length

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

方差的计算方法类似。标准差只是方差的平方根:

double stddev = Math.sqrt( variance );