Cosine Similarity Between Two 1D Embeddings

Basics
BasicsEmbeddingsRAGOpenAIAnthropicGoogle

Problem

Implement cosine_similarity(a, b) returning the cosine similarity a⋅b∥a∥2∥b∥2\frac{a \cdot b}{\|a\|_2 \|b\|_2} between two 1D vectors as a Python float. If either vector has zero L2 norm, return 0.0.

Why It Matters: Cosine similarity is the default semantic relevance metric in RAG retrieval, semantic caching, and embedding deduplication because it compares direction independent of vector magnitude.

Function Signature

import numpy as np

def cosine_similarity(a, b) -> float:
    """Return cosine similarity between two 1D embedding vectors."""

Sample Input & Output

Example 1: Parallel Vectors (Same Direction)

Input:

a = [1.0, 2.0], b = [2.0, 4.0]

Expected Output:

1.0

Explanation: b = 2 * a points in the exact same direction, so cosine similarity is 1.0.

Example 2: Orthogonal vs. Opposite Vectors

Input:

cosine_similarity([1, 0], [0, 1])  |  cosine_similarity([1, 0], [-3, 0])

Expected Output:

0.0  |  -1.0

Explanation: Perpendicular vectors have similarity 0.0; opposite directions have similarity -1.0.

Example 3: Zero Vector Edge Case

Input:

a = [0.0, 0.0], b = [1.0, 2.0]

Expected Output:

0.0

Explanation: Denominator is 0.0, so the function safely returns 0.0 instead of NaN.

Constraints & Edge Cases

  • Return a Python float in [-1.0, 1.0].
  • Output always lies in [-1.0, 1.0].
  • Return a standard Python float.

Constraints & Evaluation Criteria

  • Return a Python `float` in `[-1.0, 1.0]`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[1,0] vs [1,0] & [0,1]
Expected Output / Criteria
1.0 and 0.0