v9.1.1
Menu

Cosine Similarity Calculator

easyFREEWord EmbeddingsNLP 1: Foundations

Given two vectors as lists of floats, compute the cosine similarity between them.

Cosine similarity measures the cosine of the angle between two vectors: cosine_similarity=A⋅B∥A∥×∥B∥\text{cosine\_similarity} = \frac{A \cdot B}{\|A\| \times \|B\|}

Round the result to 4 decimal places.

Function signature: cosine_similarity(a, b)

  • a: vector A (list of floats)
  • b: vector B (list of floats, same length as a)
  • Returns: the cosine similarity as a float rounded to 4 decimal places

Example

Input
1.0,0.0,1.0
0.0,1.0,1.0
Output
0.5
Reasoning
  • Inputs: a =[1.0,0.0,1.0]= [1.0, 0.0, 1.0] and b =[0.0,1.0,1.0]= [0.0, 1.0, 1.0] are two vectors in 3-D space. Only their directions matter for the result; their lengths get divided out.
  • Dot product: multiply matching components and add: A⋅B=(1)(0)+(0)(1)+(1)(1)=1A \cdot B = (1)(0) + (0)(1) + (1)(1) = 1. Only the third coordinate, where both vectors are non-zero, contributes.
  • Magnitudes: ∥A∥=12+02+12=2≈1.4142\|A\| = \sqrt{1^2 + 0^2 + 1^2} = \sqrt{2} \approx 1.4142, and likewise ∥B∥=2\|B\| = \sqrt{2}.
  • Divide: 12⋅2=12=0.5\dfrac{1}{\sqrt{2} \cdot \sqrt{2}} = \dfrac{1}{2} = 0.5, which is already exact at 4 decimal places, so the output is 0.5.
  • Notice: cos⁡θ=0.5\cos\theta = 0.5 means the vectors are 60∘60^\circ apart. Identical directions give 1.0 and perpendicular vectors such as [1,0][1, 0] and [0,1][0, 1] give 0.0. Scaling either vector by a positive constant never changes the answer.

Constraints

  • Vectors have the same dimension
  • Output: A single float rounded to 4 decimal places
  • Vectors will not be zero vectors

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.