Linear Algebra Basics
Dot Product
Multiply two length-4 vectors element by element and accumulate the sum. The
replay shows total growing after each pairwise multiplication, making the
sum-of-products definition concrete before the single-call NumPy version.
By hand
With NumPy
np.dot(va, vb) computes the dot product in one call. The equivalent operator
va @ vb does the same for 1-D inputs. The snapshot shows both input shapes
and dtypes, then the scalar result.
naive.py
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
total = 0
for i in range(len(a)):
total += a[i] * b[i]
print('RESULT:', total)
library.py
import numpy as np
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
va = np.array(a)
vb = np.array(b)
result = int(np.dot(va, vb))
print('a: shape:', va.shape, 'dtype:', va.dtype, 'values:', va.tolist())
print('b: shape:', vb.shape, 'dtype:', vb.dtype, 'values:', vb.tolist())
print('dot product:', result)
print('RESULT:', result)
a: shape: (4,) dtype: int64 values: [1, 2, 3, 4]
b: shape: (4,) dtype: int64 values: [5, 6, 7, 8]
dot product: 70
RESULT: 70
Implementation notes
- The dot product sums pairwise products and returns a scalar, collapsing
two length-n vectors to a single number. Contrast with
elementwise-product(ch03), which multiplies position by position and returns an array of the same length — no summation occurs there. - For 1-D arrays
np.dot(a, b)anda @ bare identical. For 2-D arrays@is matrix multiplication;np.dothas subtly different broadcasting rules. Prefer@for matrix work; usenp.dotonly for 1-D dot products. - Both inputs must have the same length; mismatched shapes raise a
ValueError. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.