InferenceAI

Enter at least two characters to search.

Start free

Cosine Similarity

easyEmbeddings12 min10 XP

Implement cosine_similarity(a, b) without external libraries. Return 0.0 when either vector has zero magnitude and round the result to six decimals.

INTERACTIVE CONCEPT

Explore vector similarity

Rotate the second unit vector to see how alignment changes the cosine score.

0.71similarity

For these unit vectors, cosine similarity equals cos(angle). A zero vector needs separate handling in your solution.

0° aligned90° perpendicular180° opposite

Examples

EXAMPLE WALKTHROUGHidentical

A guided view of the published example, not a trace of your code.

INPUT[[1,0],[1,0]]
TASKcosine_similarity()
EXPECTED OUTPUT1

Start with the input values shown in this example.

Example 1 of 2

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

Output: 1

Explanation: identical

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

Output: 0

Explanation: orthogonal

Hint 1

Start with the dot product.

Hint 2

Compute each L2 norm from the sum of squared values.

Topics

PythonEmbeddingsLinear Algebra