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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28428365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:35:00  来源:igfitidea点击:

How to find correlation between two integer arrays in java

javaarraysmathintcorrelation

提问by Surjya Narayana Padhi

I am searching a lot but could not find exactly what i need till now. I have two integer arrayas int[] xand int[] y. I want to find simple linear correlationbetween 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?

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

回答by Dmitry Bychenko

Correlation is quite easy to computemanually:

相关性很容易手动计算

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;
  }

回答by Hamed Moghaddam

There is nothing in core Java. There are libraries out there you can use. Apache Commons has a statistical project, check PearsonCorrelationclass.

核心 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