code511788465541441 - 1 year ago 152
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.

``````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];
}
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download