# Calculate the Sample Covariance

Page 1 of 1

## 0 Replies - 1840 Views - Last Post: 03 April 2012 - 05:58 AM

### #1 Ryano121

• D.I.C Lover

Reputation: 1461
• Posts: 3,289
• Joined: 30-January 11

# Calculate the Sample Covariance

Posted 03 April 2012 - 05:58 AM

Description: See Example Usage in snippetIn probability theory and statistics, covariance is a measure of how much two random variables change together. More information - http://en.wikipedia....wiki/Covariance
```public class Covariance
{
public static double sampleCovariance(double[] x, double[] y)
{
// means of each data set
double xMean = mean(x);
double Mmean = mean(y);

double result = 0;

for(int i = 0;i < x.length; i++)
{
// sum the product of the deviations with the means
result += ((x[i] - xMean) * (y[i] - yMean));
}

// divide by data size - 1 to get the estimated covariance from a sample
result /= (x.length - 1);

return result;
}

// Get the mean of a data set
private static double mean(double[] data)
{
double sum = 0;

for (int i = 0; i < data.length; i++)
{
sum += data[i];
}

return sum / data.length;
}

public static void main(String[] args)
{

double[] x = { 2, 3, 4, 5, 6, 8, 10, 11.53542 };

double[] y = { 21.05, 23.51, 24.23, 27.71, 30.86, 45.85, 52.12, 55.98 };

double result = Covariance.sampleCovariance(x, y);
System.out.println("Sample Covariance = " + result);
}
}

// OUTPUT

// Sample Covariance = 46.45166951071428
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }