How to Calculate the Dot Product in Python Without NumPy?

In this tutorial, I will explain how to calculate the dot product of two vectors in Python without using the NumPy library. The dot product is a fundamental operation in linear algebra with many applications in machine learning, computer graphics, and physics simulations. While the NumPy library provides a convenient dot() function to compute dot products, it’s useful to understand how to implement it from scratch using pure Python.

As a data scientist working on a machine learning project, I recently ran into a situation where I needed to compute dot products but couldn’t rely on NumPy due to environment constraints. After searching online, I found that calculating the dot product without NumPy is actually easy using basic Python programming constructs. Let me show you how to do this.

What is the Dot Product?

The dot product (also known as the scalar product) of two vectors a and b is defined as:

$\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i$

Where $a_i$ and $b_i$ are the $i$-th elements of vectors a and b respectively, and $n$ is the dimension of the vectors.

In other words, to calculate the dot product, we multiply the corresponding elements of the two vectors and sum up the results. The dot product results in a scalar value.

Check out raw input function in Python

Calculate the Dot Product in Python

Now let’s see how to implement the dot product calculation in Python without using NumPy. We’ll start with a simple example and then generalize it to vectors of any size.

Example 1: Dot Product of Two 3D Vectors

Suppose we have two 3D vectors represented as Python lists:

a = [1, 2, 3] 
b = [4, 5, 6]

To calculate their dot product, we can multiply the corresponding elements and sum the results:

dot_product = a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
print(dot_product)  # Output: 32

This matches the expected result: $1 * 4 + 2 * 5 + 3 * 6 = 32$

Here is the exact output in the screenshot below:

dot product python without numpy

Example 2: Generalizing to Vectors of Any Size

To handle vectors of any size, we can use a loop to iterate over the elements and accumulate the sum. Here’s a Python function that calculates the dot product of two vectors of equal size:

def dot_product(a, b):
    if len(a) != len(b):
        raise ValueError("Vectors must have same length")
    
    result = 0
    for i in range(len(a)):
        result += a[i] * b[i]
    
    return result

The function first checks that the input vectors have the same length, raising a ValueError if they don’t. It then initializes a result variable to accumulate the sum. The loop iterates over the indices of the vectors using range(len(a)), multiplies the corresponding elements, and adds the product to result.

Let’s test it out with some example vectors:

vector1 = [2.5, -1.0, 3.2] 
vector2 = [1.2, 4.7, -0.8]

dot_prod = dot_product(vector1, vector2)
print(f"The dot product is: {dot_prod:.2f}")
# Output: The dot product is: -4.26

Great, it works as expected!

Here is the complete code:

def dot_product(a, b):
    if len(a) != len(b):
        raise ValueError("Vectors must have same length")
    
    result = 0
    for i in range(len(a)):
        result += a[i] * b[i]
    
    return result

vector1 = [2.5, -1.0, 3.2] 
vector2 = [1.2, 4.7, -0.8]
dot_prod = dot_product(vector1, vector2)
print(f"The dot product is: {dot_prod:.2f}")

Here is the exact output in the screenshot below:

Calculate the Dot Product in Python Without NumPy

Check out linear search and binary search in Python program

Applications and Performance Considerations

The dot product has numerous applications across different domains. Here are a few examples:

  • In machine learning, the dot product is used extensively in algorithms like linear regression, support vector machines (SVM), and neural networks for tasks such as computing similarities between feature vectors or updating model weights during training.
  • In computer graphics, the dot product is fundamental for operations like vector projection, determining angles between vectors, and calculating lighting in 3D scenes.
  • In physics simulations, the dot product appears in formulas for work, energy, and force calculations.

Conclusion

In this tutorial, we learned how to calculate the dot product of two vectors in Python without relying on the NumPy library. I discussed the mathematical formula, implemented a generalizable function using a loop, and discussed some applications and performance considerations.

To summarize:

  • The dot product of two vectors is the sum of the products of their corresponding elements
  • It can be calculated in pure Python using a loop to multiply elements and accumulate the sum
  • The vectors must have equal lengths for the dot product to be defined
  • While pure Python is simple to understand, using optimized libraries like NumPy is much faster for large-scale computations

I hope this post helped clarify the concept of dot products and how to compute them in Python. Feel free to reach out with any questions!

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.