【发布时间】:2015-02-10 09:39:17
【问题描述】:
我搜索了很多,但直到现在都找不到我需要的东西。
我有两个整数数组int[] x 和int[] y。我想在这两个整数数组之间找到简单的线性相关,它应该将结果返回为double。在java中你知道提供这个或任何代码sn-p的任何库函数吗?
【问题讨论】:
标签: java arrays math int correlation
我搜索了很多,但直到现在都找不到我需要的东西。
我有两个整数数组int[] x 和int[] y。我想在这两个整数数组之间找到简单的线性相关,它应该将结果返回为double。在java中你知道提供这个或任何代码sn-p的任何库函数吗?
【问题讨论】:
标签: java arrays math int correlation
核心 Java 中没有任何内容。那里有你可以使用的库。 Apache Commons 有一个 statistical project,请查看 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 在旧时编译器上可能会更快一些(无需返回先前的状态)。只是英特尔 8086 时代和C 编译器的习惯......