Java Array Covariance covariance(int[] v1, int[] v2)

Here you can find the source of covariance(int[] v1, int[] v2)

Description

Computes the covariance.

License

Open Source License

Declaration

public static double covariance(int[] v1, int[] v2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from  w  ww.  ja  va2 s .  co  m
     * Computes the covariance.
     */
    public static double covariance(double[] v1, double[] v2) {
        if (v1.length != v2.length)
            throw new IllegalArgumentException(
                    "Arrays must have the same length : " + v1.length + ", " + v2.length);
        final double m1 = mean(v1);
        final double m2 = mean(v2);
        double ans = 0.0;
        for (int i = 0; i < v1.length; i++)
            ans += (v1[i] - m1) * (v2[i] - m2);
        return ans / (v1.length - 1);
    }

    /**
     * Computes the covariance.
     */
    public static double covariance(int[] v1, int[] v2) {
        if (v1.length != v2.length)
            throw new IllegalArgumentException(
                    "Arrays must have the same length : " + v1.length + ", " + v2.length);
        final double m1 = mean(v1);
        final double m2 = mean(v2);
        double ans = 0.0;
        for (int i = 0; i < v1.length; i++)
            ans += (v1[i] - m1) * (v2[i] - m2);
        return ans / (v1.length - 1);
    }

    /**
     * Computes the mean.
     */
    public static double mean(double[] v) {
        if (v.length == 0)
            throw new IllegalArgumentException("Nothing to compute! The array must have at least one element.");
        return (mass(v) / (double) v.length);
    }

    /**
     * Computes the mean.
     */
    public static double mean(int[] v) {
        if (v.length == 0)
            throw new IllegalArgumentException("Nothing to compute! The array must have at least one element.");
        return (mass(v) / (double) v.length);
    }

    /**
     * Returns the sum of the elements of the array.
     */
    public static double mass(double[] v) {
        double somme = 0.0;
        for (int k = 0; k < v.length; k++) {
            somme += v[k];
        }
        return (somme);
    }

    /**
     * Returns the sum of the elements of the array.
     */
    public static int mass(int[] v) {
        int somme = 0;
        for (int k = 0; k < v.length; k++) {
            somme += v[k];
        }
        return (somme);
    }
}

Related

  1. covariance(double[] a, double[] b)
  2. covariance(double[] x, double[] y)
  3. covariance(double[] x, double[] y, int delay)
  4. covariance(final double[] xArray, final double[] yArray)
  5. covariance(final double[][] data)
  6. covariance(Number[] x, Number[] y)
  7. covarianceOfDoubleArrays(double[] x, double[] y)
  8. covarianceTwoColumns(double[][] data, int col1, int col2)