Dot Product

Basic Definition

The dot product takes two vectors of equal dimension and returns a single scalar (number). For two vectors a and b, it’s denoted as a · b.

How to Calculate It

For 2D vectors a = (a₁, a₂) and b = (b₁, b₂): a · b = a₁b₁ + a₂b₂

For 3D vectors a = (a₁, a₂, a₃) and b = (b₁, b₂, b₃): a · b = a₁b₁ + a₂b₂ + a₃b₃

In general, you multiply corresponding components and sum them up.

Geometric Interpretation

The dot product has a beautiful geometric meaning: a · b = |a| |b| cos(θ)

Where |a| and |b| are the magnitudes (lengths) of the vectors, and θ is the angle between them.

This means:

  • If the dot product is positive, the angle is acute (< 90°)
  • If it’s zero, the vectors are perpendicular (90°)
  • If it’s negative, the angle is obtuse (> 90°)

Key Applications

The dot product appears everywhere in mathematics, physics, and computer science:

Physics: Calculating work done by a force (W = F · d), where force and displacement are vectors

Computer Graphics: Determining lighting angles, checking if surfaces face toward or away from cameras

Machine Learning: Measuring similarity between feature vectors, computing attention scores in neural networks

Projections: Finding how much of one vector points in the direction of another

Important Properties

The dot product is:

  • Commutative: a · b = b · a
  • Distributive: a · (b + c) = a · b + a · c
  • Related to vector length: a · a = |a

The dot product is one of those mathematical tools that seems simple but has profound applications across many fields. Its ability to relate algebraic operations to geometric concepts like angles and projections makes it particularly powerful.

In Python


# Micropip is used by the CodeEmitter Obsidian plugin to install packages
import micropip
await micropip.install('numpy')  


# Method 1: Using NumPy (most common and efficient)
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

dot_product = np.dot(a, b)
print(f"Dot product: {dot_product}")  # Output: 32
# Calculation: (1*4) + (2*5) + (3*6) = 4 + 10 + 18 = 32


# Method 2: Using @ operator (NumPy)
dot_product = a @ b
print(f"Dot product: {dot_product}")  # Output: 32


# Method 3: Manual calculation (without NumPy)
a = [1, 2, 3]
b = [4, 5, 6]

dot_product = sum(x * y for x, y in zip(a, b))
print(f"Dot product: {dot_product}")  # Output: 32


# Method 4: Using a loop
dot_product = 0
for i in range(len(a)):
    dot_product += a[i] * b[i]
print(f"Dot product: {dot_product}")  # Output: 32