cosineSimilarity static method

double cosineSimilarity(
  1. List<double> a,
  2. List<double> b
)

Computes cosine similarity between two embeddings.

Implementation

static double cosineSimilarity(List<double> a, List<double> b) {
  if (a.length != b.length) {
    throw ArgumentError('Embeddings must have the same dimension');
  }

  var dotProduct = 0.0;
  var normA = 0.0;
  var normB = 0.0;

  for (var i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }

  if (normA == 0 || normB == 0) return 0;

  return dotProduct / (math.sqrt(normA) * math.sqrt(normB));
}