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

#1 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • 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