Skip to content

Instantly share code, notes, and snippets.

@joninsky
Last active February 6, 2024 16:05
Show Gist options
  • Save joninsky/4a8773f13fb5ff4513060ef03c8035d7 to your computer and use it in GitHub Desktop.
Save joninsky/4a8773f13fb5ff4513060ef03c8035d7 to your computer and use it in GitHub Desktop.
Cosine Similarity in Swift
/** 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