How to Compute Cosine Similarity Between Two Vectors in Python

This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

19 lines
Python 3.9+
import math

def cosine_similarity(vec_a, vec_b):
    if len(vec_a) != len(vec_b):
        raise ValueError("Vectors must have the same length")
    
    dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
    norm_a = math.sqrt(sum(a * a for a in vec_a))
    norm_b = math.sqrt(sum(b * b for b in vec_b))
    
    if norm_a == 0 or norm_b == 0:
        return 0.0
    
    return dot_product / (norm_a * norm_b)

if __name__ == "__main__":
    vec1 = [1, 2, 3]
    vec2 = [4, 5, 6]
    print(cosine_similarity(vec1, vec2))

Output

stdout
0.9746318461970762

How it works

The function first validates that both vectors have the same length. It then computes the dot product of the two vectors and their Euclidean norms (square root of the sum of squares). The cosine similarity is the dot product divided by the product of the norms. If either norm is zero, it returns 0.0 to avoid division by zero. The result measures the cosine of the angle between the two vectors, where 1 means identical direction, 0 means orthogonal, and -1 means opposite directions.

Common mistakes

  • Forgetting to check that vectors have the same length, causing a zip() to silently ignore extra elements.
  • Not handling the case where a vector is all zeros, leading to a division by zero error.
  • Using integer division or truncation instead of float division, losing the fractional part.

Variations

  1. Use numpy: np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) for large vectors.
  2. Use scipy.spatial.distance.cosine for a direct one-liner implementation.

Real-world use cases

  • Computing similarity between document embeddings for a search or recommendation system.
  • Comparing user preference vectors to find similar users in a collaborative filtering engine.
  • Measuring the similarity between feature vectors in a machine learning model for clustering.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.