Problems
Loading...
1 / 1

Implement Cosine Similarity

Linear Algebra
Easy

Implement a function to compute the cosine similarity between two vectors a and b.

Cosine similarity measures the angle between two vectors in a high-dimensional space.

cosine_similarity(a,b)=abab\text{cosine\_similarity}(a, b) = \frac{a \cdot b}{||a|| \, ||b||}

where:

  • a · b is the dot product
  • ||a|| and ||b|| are the Euclidean norms of a and b
Loading visualization...

Examples

Input: a=[1,2,3], b=[2,4,6]

Output: 1.0 (perfect alignment)

Input: a=[1,0], b=[0,1]

Output: 0.0 (orthogonal)

Hint 1

Use np.dot() for dot product and np.linalg.norm() for norms.

Hint 2

Handle zero vectors gracefully by checking if either norm is 0 and returning 0.0 in that case.

Requirements

  • Input: 1D NumPy arrays of equal length
  • Output: scalar float
  • Must be fully vectorized (no loops)
  • Handle zero vectors gracefully (return 0 if either norm is 0)

Constraints

  • len(a) == len(b) ≤ 10⁶
  • Use only NumPy
Try Similar Problems