public static double cosineSimilarity ( float [ ] x , float [ ] y , double normY ) { int length = x . length ; double dot = 0.0 ; double totalXSq = 0.0 ; for ( int i = 0 ; i < length ; i ++ ) { double xi = x [ i ] ; totalXSq += xi * xi ; dot += xi * y [ i ] ; } return dot / ( Math . sqrt ( totalXSq ) * normY ) ; }
Computes cosine similarity of values in two given arrays when the norm of one array is known in advance which is a not - uncommon case .