Last active
February 6, 2024 16:05
-
-
Save joninsky/4a8773f13fb5ff4513060ef03c8035d7 to your computer and use it in GitHub Desktop.
Cosine Similarity in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Cosine similarity **/ | |
private func cosineSim(A: [Double], B: [Double]) -> Double { | |
return dot(A: A, B: B) / (magnitude(A: A) * magnitude(A: B)) | |
} | |
/** Dot Product **/ | |
private func dot(A: [Double], B: [Double]) -> Double { | |
var x: Double = 0 | |
for i in 0...A.count-1 { | |
x += A[i] * B[i] | |
} | |
return x | |
} | |
/** Vector Magnitude **/ | |
private func magnitude(A: [Double]) -> Double { | |
var x: Double = 0 | |
for elt in A { | |
x += elt * elt | |
} | |
return sqrt(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment