Correlation of two arrays in C#

前端 未结 6 971
挽巷
挽巷 2020-11-29 05:09

Having two arrays of double values, I want to compute correlation coefficient (single double value, just like the CORREL function in MS Excel). Is there some simple one-line

6条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:08

    In order to calculate Pearson product-moment correlation coefficient

    http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient

    You can use this simple code:

      public static Double Correlation(Double[] Xs, Double[] Ys) {
        Double sumX = 0;
        Double sumX2 = 0;
        Double sumY = 0;
        Double sumY2 = 0;
        Double sumXY = 0;
    
        int n = Xs.Length < Ys.Length ? Xs.Length : Ys.Length;
    
        for (int i = 0; i < n; ++i) {
          Double x = Xs[i];
          Double y = Ys[i];
    
          sumX += x;
          sumX2 += x * x;
          sumY += y;
          sumY2 += y * y;
          sumXY += x * y;
        }
    
        Double stdX = Math.Sqrt(sumX2 / n - sumX * sumX / n / n);
        Double stdY = Math.Sqrt(sumY2 / n - sumY * sumY / n / n);
        Double covariance = (sumXY / n - sumX * sumY / n / n);
    
        return covariance / stdX / stdY; 
      }
    

提交回复
热议问题