如何在java中找到两个整数数组之间的相关性

我正在寻找很多,但直到现在才找到我需要的东西。 我有两个整数arrayas int [] x和int [] y。 我想在这两个整数数组之间找到简单的线性相关,它应该将结果返回为double。 在java中你知道提供这个或任何代码片段的任何库函数吗?

相关性很容易计算:

http://en.wikipedia.org/wiki/Correlation_and_dependence

public static double Correlation(int[] xs, int[] ys) { //TODO: check here that arrays are not null, of the same length etc double sx = 0.0; double sy = 0.0; double sxx = 0.0; double syy = 0.0; double sxy = 0.0; int n = xs.length; for(int i = 0; i < n; ++i) { double x = xs[i]; double y = ys[i]; sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y; } // covariation double cov = sxy / n - sx * sy / n / n; // standard error of x double sigmax = Math.sqrt(sxx / n - sx * sx / n / n); // standard error of y double sigmay = Math.sqrt(syy / n - sy * sy / n / n); // correlation is just a normalized covariation return cov / sigmax / sigmay; } 

核心Java中没有任何内容。 你可以使用库。 Apache Commons有一个统计项目 ,检查PearsonCorrelation类。

示例代码:

 public static void main(String[] args) { double[] x = {1, 2, 4, 8}; double[] y = {2, 4, 8, 16}; double corr = new PearsonsCorrelation().correlation(y, x); System.out.println(corr); } 

打印出1.0

Interesting Posts