Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you calculate the variance, median, and standard deviation in C++ or Java? [duplicate]

Tags:

java

c++

math

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

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

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

like image 736
code511788465541441 Avatar asked Nov 02 '11 23:11

code511788465541441


1 Answers

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];
    }
}
like image 124
Dennis Avatar answered Nov 14 '22 16:11

Dennis