Neural Mastery
← Practice
Cosine Similarity Between Vectorseasy

Cosine Similarity Between Vectors

easy RAG & Retrieval 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Interactive Vector Lab

Cosine Similarity

Angular alignment in vector space: cos(θ) = (a · b) / (||a|| ||b||)
Editable Inputs (change values live)Step 0 of 4
u =
v =
Cosine similarity measures angular alignment between two vectors, normalized to [-1, 1].
Formula: cos(θ) = (a · b) / (||a|| ||b||)
Live Result0.996

Implement cosine similarity, the default relevance metric embedding-based semantic search and RAG retrieval use because it measures directional alignment, ignoring magnitude.

Task

Implement cosine_similarity(a, b) returning (a . b) / (||a|| * ||b||). Libraries (NumPy) are allowed; a plain-Python solution earns 10 bonus points.

Function Signature

cosine_similarity(a: list[float], b: list[float]) -> float

Examples

Example 1: Orthogonal Vectors
Input: a = [1, 0] b = [0, 1]
Output: 0
Explanation: Perpendicular vectors have similarity 0
Example 2: Identical Direction
Input: a = [1, 1] b = [1, 1]
Output: 1
Example 3: Opposite Direction
Input: a = [1, 0] b = [-1, 0]
Output: -1

Constraints

  • Libraries (NumPy) are allowed and accepted normally.
  • A plain-Python solution earns 10 bonus points.
  • Must raise ValueError if len(a) != len(b).
  • Must raise ValueError if either vector has zero magnitude (undefined direction).
Python3Saved ✓
import math

def cosine_similarity(a: list[float], b: list[float]) -> float:
"""Return the cosine similarity between two equal-length vectors, in [-1, 1].
Raise ValueError if len(a) != len(b), or if either vector has zero magnitude."""
# Your implementation here
pass

Case 1: Orthogonal Vectors
Input: a = [1, 0] b = [0, 1]
Expected: 0
Case 2: Identical Direction
Input: a = [1, 1] b = [1, 1]
Expected: 1
Case 3: Opposite Direction
Input: a = [1, 0] b = [-1, 0]
Expected: -1