I am searching a lot but could not find exactly what i need till now. I have two integer arrayas int[] x and int[] y. I want to find simple linear correlation between these two integer arrays and it should return the result as double. In java do you know any library function providing this or any code snippet?
我正在寻找很多,但直到现在才找到我需要的东西。我有两个整数arrayas int [] x和int [] y。我想在这两个整数数组之间找到简单的线性相关,它应该将结果返回为double。在java中你知道提供这个或任何代码片段的任何库函数吗?
2 个解决方案
#1
9
Correlation is quite easy to compute:
相关性很容易计算:
http://en.wikipedia.org/wiki/Correlation_and_dependence
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;
}
#2
5
There is nothing in core Java. There are libraries out there you can use. Apache Commons has a statistical project, check PearsonCorrelation class.
核心Java中没有任何内容。你可以使用库。 Apache Commons有一个统计项目,检查PearsonCorrelation类。
Sample code:
示例代码:
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);
}
prints out 1.0
打印出1.0
#1
9
Correlation is quite easy to compute:
相关性很容易计算:
http://en.wikipedia.org/wiki/Correlation_and_dependence
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;
}
#2
5
There is nothing in core Java. There are libraries out there you can use. Apache Commons has a statistical project, check PearsonCorrelation class.
核心Java中没有任何内容。你可以使用库。 Apache Commons有一个统计项目,检查PearsonCorrelation类。
Sample code:
示例代码:
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);
}
prints out 1.0
打印出1.0