Cosine Similarity

MediumMachine LearningMath

Description

Given two equal-length non-zero vectors a and b, return their cosine similarity (dot product divided by the product of their magnitudes), rounded to 4 decimal places.

Examples

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

Normalizing the dot product by both magnitudes gives a similarity of 0.

Input:a = [1,2,3], b = [1,2,3]
Output:1
Explanation:

Normalizing the dot product by both magnitudes gives a similarity of 1.

Input:a = [1,1], b = [2,2]
Output:1
Explanation:

Normalizing the dot product by both magnitudes gives a similarity of 1.

Constraints

  • 1 ≤ a.length ≤ 10⁴

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.