我一直在搜索,但到目前为止还没有找到我需要的东西。
我有两个整数数组int [] x
和int [] y
。我想要找到这两个整数数组之间的简单线性相关性,并将结果作为double
返回。在Java中,您是否知道提供此功能的任何库函数或任何代码片段?
我一直在搜索,但到目前为止还没有找到我需要的东西。
我有两个整数数组int [] x
和int [] y
。我想要找到这两个整数数组之间的简单线性相关性,并将结果作为double
返回。在Java中,您是否知道提供此功能的任何库函数或任何代码片段?
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
相关性在手动计算时相当容易:不需要使用任何特殊工具。
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;
}
i++
或++i
;在旧的编译器上,++i
可能会更快(无需返回先前的状态)。这只是Intel 8086时代和为它们编写的C
编译器的一个习惯... - Dmitry Bychenko