code511788465541441 code511788465541441 - 3 months ago 33
C++ Question

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


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.

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

    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;
       } 
       else 
       {
          return data[data.length / 2];
       }
    }
}