如何计算c++或Java中的方差、中值和标准差?(复制)

时间:2022-09-02 09:14:02

Possible Duplicate:
Simple statistics - Java packages for calculating mean, standard deviation, etc

可能的重复:简单统计—用于计算平均值、标准偏差等的Java包

I have a vector of some doubles (1.1,2,3,5). How can I calculate the variance, median, and standard deviation?

我有一个向量(1。1 2 3 5)如何计算方差,中位数和标准差?

Java or C++ or even pseudo code would do.

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

2 个解决方案

#1


99  

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

#2


1  

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

要计算平均值,循环遍历数字的列表/数组,跟踪部分和和的长度。然后返回/长度之和。

double sum = 0.0;
int length = 0;

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

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

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

double stddev = Math.sqrt( variance );

#1


99  

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

#2


1  

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

要计算平均值,循环遍历数字的列表/数组,跟踪部分和和的长度。然后返回/长度之和。

double sum = 0.0;
int length = 0;

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

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

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

double stddev = Math.sqrt( variance );