Retrieval & Ranking · Easy
Cosine Similarity
Compare vectors while handling zero norms safely.
Task
Implement cosine_similarity(a: list[float], b: list[float]) -> float. Compute the cosine similarity between two vectors with stable norm calculations.
Requirements
- a and b are non-empty one-dimensional vectors of the same length containing finite numeric values.
- Compute the dot product divided by the product of the two Euclidean norms.
- If either vector has zero norm, return 0.0.
- Avoid overflow and underflow by scaling each nonzero vector by its own maximum absolute component before computing the dot product and norms.
- Clamp the final result to the mathematical range [-1.0, 1.0] to remove tiny floating-point overshoots.
- Return a scalar and do not mutate either input.
Example
cosine_similarity([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
# 0.9746318461970762