B4J Question cosine similarity of 2 vectors

peacemaker

Expert
Licensed User
Longtime User
Hi, All

Any example of comparing two Arrays As float (0.0, 0.1, 0.2) ?
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Yes, solved:
B4X:
Sub Vectors_Similarity(v1() As Float, v2() As Float) As Float
    If v1.Length <> v2.Length Then Return 0.0
    Dim dotProduct As Double = 0.0
    Dim normA As Double = 0.0
    Dim normB As Double = 0.0
    
    For i = 0 To v1.Length - 1
        dotProduct = dotProduct + v1(i) * v2(i)
        normA = normA + Power(v1(i), 2)
        normB = normB + Power(v2(i), 2)
    Next
    Dim res As Double = dotProduct / (Sqrt(normA) * Sqrt(normB))
    Return res.As(Float)
End Sub
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
But if to compare 2 zero vectors - deleting to zero will give NaN :)
 
Upvote 0
Top