cosineSimilarity function

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

Computes cosine similarity between two vectors (0.0 = orthogonal, 1.0 = identical direction). Standard RAG similarity metric.

Implementation

double cosineSimilarity(List<double> a, List<double> b) {
  if (a.length != b.length) {
    throw ArgumentError(
      'vectors must have the same length '
      '(${a.length} vs ${b.length})',
    );
  }
  var dot = 0.0, normA = 0.0, normB = 0.0;
  for (var i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  final d = math.sqrt(normA) * math.sqrt(normB);
  return d == 0 ? 0.0 : dot / d;
}