public static double cosineSimilarity ( double [ ] a , double [ ] b ) { check ( a , b ) ; double dotProduct = 0.0 ; double aMagnitude = 0.0 ; double bMagnitude = 0.0 ; for ( int i = 0 ; i < b . length ; i ++ ) { double aValue = a [ i ] ; double bValue = b [ i ] ; aMagnitude += aValue * aValue ; bMagnitude += bValue * bValue ; dotProduct += aValue * bValue ; } aMagnitude = Math . sqrt ( aMagnitude ) ; bMagnitude = Math . sqrt ( bMagnitude ) ; return ( aMagnitude == 0 || bMagnitude == 0 ) ? 0 : dotProduct / ( aMagnitude * bMagnitude ) ; }
Returns the cosine similarity of the two arrays .