cosineDistance function

double cosineDistance (
  1. List<double> vector1,
  2. List<double> vector2
)

Cosine Similarity between two vectors

1 = Max distance, 0 = No distance (same document)

Implementation

double cosineDistance(List<double> vector1, List<double> vector2) {
  double upper = 0;
  double bottomA = 0;
  double bottomB = 0;
  int len = min(vector1.length, vector2.length);
  for (int i = 0; i < len; i++) {
    upper += vector1[i] * vector2[i];
    bottomA += vector1[i] * vector1[i];
    bottomB += vector2[i] * vector2[i];
  }
  double diviser = sqrt(bottomA) * sqrt(bottomB);
  return 1.0 - (diviser != 0 ? (upper / diviser) : 0);
}