Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中找到两个整数数组之间的相关性_Java_Arrays_Math_Int_Correlation - Fatal编程技术网

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

如何在java中找到两个整数数组之间的相关性,java,arrays,math,int,correlation,Java,Arrays,Math,Int,Correlation,我找了很多东西,但直到现在都找不到我真正需要的东西。 我有两个整数数组int[]x和int[]y。我想找到这两个整数数组之间的简单线性相关性,它应该返回结果为double。在java中,您知道提供这个或任何代码片段的库函数吗?核心java中没有任何内容。有一些库你可以使用。apachecommons有一个check类 示例代码: public static void main(String[] args) { double[] x = {1, 2, 4, 8}; double[]

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

核心java中没有任何内容。有一些库你可以使用。apachecommons有一个check类

示例代码:

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

手动计算相关性非常容易:

公共静态双相关(int[]xs,int[]ys){
//TODO:在这里检查数组是否不为空、长度是否相同等
双sx=0.0;
双sy=0.0;
双sxx=0.0;
双syy=0.0;
双sxy=0.0;
int n=xs.length;
对于(int i=0;i
@Mvorisek:它可以是
i++
++i
<代码>++i在旧编译器上可以快一点(不需要返回以前的状态)。只是英特尔8086时代和
C
编译器给他们的一个习惯…这不包括X和Y长度不同的情况。@htellez:相关性(甚至协变量)希望长度相等,或者应该扩展标准相关性的定义。
  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;
  }