PIXELBANKv8.2.1
Menu

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)=ABA×B\text{cosine\_similarity}(A, B) = \frac{A \cdot B}{\|A\| \times \|B\|}

Where:

  • AB=iAi×BiA \cdot B = \sum_i A_i \times B_i (dot product)
  • A=iAi2\|A\| = \sqrt{\sum_i A_i^2} (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

Test Results

0/0
Run code to see test results.