Cosine Similarity: Direction, Not Length

Linear AlgebraEasy+10 XP+10

Cosine Similarity: Direction, Not Length

Cosine similarity asks a single question about two vectors: do they point the same way? It ignores length entirely, which is why it's the default distance measure for embeddings — a long document and a short one about the same subject should still count as similar.

cos(a, b) = (a · b) / (‖a‖ · ‖b‖)

The result runs from 1 (identical direction) through 0 (perpendicular) to -1 (opposite).

Task: write cosine_similarity(a, b) for two equal-length lists, returning a float rounded to 4 decimal places.

  • If either vector is all zeros its direction is undefined — return 0.0 rather than dividing by zero.

Examples

a = [1.0, 0.0]
b = [0.0, 1.0]
returns 0.0
a = [1.0, 2.0, 3.0]
b = [2.0, 4.0, 6.0]
returns 1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run