📘
Cosine Similarity
Calculate the cosine similarity between two vectors.
Cosine similarity measures the angle between two vectors, regardless of their magnitude:
cosine_similarity(A,B)=∥A∥×∥B∥A⋅B
Where:
- A⋅B=∑iAi×Bi (dot product)
- ∥A∥=∑iAi2 (Euclidean norm)
This is widely used in NLP to measure document or word similarity.
Input format:
- Line 1: Space-separated floats for vector A
- Line 2: Space-separated floats for vector B
Output: Cosine similarity rounded to 4 decimal places.
Example:
Input:
1 2 3 4 5 6
Output:
0.9746
Reasoning:
Step 1: Compute dot product A . B = 14 + 25 + 3*6 = 4 + 10 + 18 = 32
Step 2: Compute norms ||A|| = sqrt(1 + 4 + 9) = sqrt(14) = 3.7417 ||B|| = sqrt(16 + 25 + 36) = sqrt(77) = 8.7749
Step 3: Compute cosine similarity cos_sim = 32 / (3.7417 * 8.7749) = 32 / 32.8329 = 0.9746
Constraints:
- Both vectors have the same length
- Vectors are non-zero
- Use only math module (no numpy)
- Round result to 4 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.