Calculate the covariance of two sets of data. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Calculate the covariance of two sets of data.

Demo Code


//package com.java2s;

public class Main {
    /**/* w w  w .  jav a2  s . co  m*/
     * Calculate the covariance of two sets of data.
     *
     * @param x
     *          The first set of data
     * @param y
     *          The second set of data
     * @return The covariance of x and y
     */
    public static double covariance(double[] x, double[] y) {
        double xmean = mean(x);
        double ymean = mean(y);

        double result = 0;

        for (int i = 0; i < x.length; i++) {
            result += (x[i] - xmean) * (y[i] - ymean);
        }

        result /= x.length - 1;

        return result;
    }

    /**
     * Calculate the mean of a data set
     *
     * @param data The data set to calculate the mean of
     * @return The mean of the data set
     */
    public static double mean(double[] data) {
        double sum = 0;

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

        return sum / data.length;
    }
}

Related Tutorials