< Summary

Information
Class: Intentum.AI.Similarity.CosineSimilarityHelper
Assembly: Intentum.AI
File(s): /home/runner/work/Intentum/Intentum/src/Intentum.AI/Similarity/CosineSimilarityHelper.cs
Line coverage
100%
Covered lines: 15
Uncovered lines: 0
Coverable lines: 15
Total lines: 47
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
CosineSimilarity(...)100%88100%
CosineSimilarityNormalized(...)100%11100%

File(s)

/home/runner/work/Intentum/Intentum/src/Intentum.AI/Similarity/CosineSimilarityHelper.cs

#LineLine coverage
 1namespace Intentum.AI.Similarity;
 2
 3/// <summary>
 4/// Standard cosine similarity implementation.
 5/// </summary>
 6public static class CosineSimilarityHelper
 7{
 8    /// <summary>
 9    /// Computes cosine similarity between two vectors. Returns a value in [-1, 1] range.
 10    /// 1 means identical direction, 0 means orthogonal, -1 means opposite direction.
 11    /// </summary>
 12    /// <param name="a">First vector.</param>
 13    /// <param name="b">Second vector.</param>
 14    /// <returns>Cosine similarity in [-1, 1].</returns>
 15    /// <exception cref="ArgumentException">Thrown when vectors have different lengths.</exception>
 16    public static double CosineSimilarity(double[] a, double[] b)
 2117    {
 2118        if (a.Length != b.Length)
 119            throw new ArgumentException("Vectors must have the same length");
 20
 6021        double dotProduct = 0, normA = 0, normB = 0;
 22
 21623        for (int i = 0; i < a.Length; i++)
 8824        {
 8825            dotProduct += a[i] * b[i];
 8826            normA += a[i] * a[i];
 8827            normB += b[i] * b[i];
 8828        }
 29
 30        const double epsilon = 1e-10;
 2031        if (normA < epsilon || normB < epsilon)
 332            return 0;
 33
 1734        return dotProduct / (Math.Sqrt(normA) * Math.Sqrt(normB));
 2035    }
 36
 37    /// <summary>
 38    /// Computes cosine similarity normalized to [0, 1] range.
 39    /// 1 means identical direction, 0.5 means orthogonal, 0 means opposite direction.
 40    /// </summary>
 41    /// <param name="a">First vector.</param>
 42    /// <param name="b">Second vector.</param>
 43    /// <returns>Normalized cosine similarity in [0, 1].</returns>
 44    /// <exception cref="ArgumentException">Thrown when vectors have different lengths.</exception>
 45    public static double CosineSimilarityNormalized(double[] a, double[] b)
 1646        => (CosineSimilarity(a, b) + 1) / 2;
 47}