public static double weightedCoefficient ( NumberVector x , NumberVector y , double [ ] weights ) { final int xdim = x . getDimensionality ( ) ; final int ydim = y . getDimensionality ( ) ; if ( xdim != ydim ) { throw new IllegalArgumentException ( "Invalid arguments: number vectors differ in dimensionality." ) ; } if ( xdim != weights . length ) { throw new IllegalArgumentException ( "Dimensionality doesn't agree to weights." ) ; } if ( xdim == 0 ) { throw new IllegalArgumentException ( "Empty vector." ) ; } // Inlined computation of Pearson correlation, to avoid allocating objects! // This is a numerically stabilized version, avoiding sum-of-squares. double sumXX = 0. , sumYY = 0. , sumXY = 0. , sumWe = weights [ 0 ] ; double sumX = x . doubleValue ( 0 ) * sumWe , sumY = y . doubleValue ( 0 ) * sumWe ; for ( int i = 1 ; i < xdim ; ++ i ) { final double xv = x . doubleValue ( i ) , yv = y . doubleValue ( i ) , w = weights [ i ] ; // Delta to previous mean final double deltaX = xv * sumWe - sumX ; final double deltaY = yv * sumWe - sumY ; // Increment count first final double oldWe = sumWe ; // Convert to double! sumWe += w ; final double f = w / ( sumWe * oldWe ) ; // Update sumXX += f * deltaX * deltaX ; sumYY += f * deltaY * deltaY ; // should equal deltaY * neltaX! sumXY += f * deltaX * deltaY ; // Update sums sumX += xv * w ; sumY += yv * w ; } // One or both series were constant: if ( ! ( sumXX > 0. && sumYY > 0. ) ) { return ( sumXX == sumYY ) ? 1. : 0. ; } return sumXY / FastMath . sqrt ( sumXX * sumYY ) ; }
Compute the Pearson product - moment correlation coefficient for two NumberVectors .