Use np.linalg.norm(a - b) (or np.linalg.norm(A - B, axis=1) for row-wise batch distances across 2D arrays)—which delegates directly to optimized BLAS routines to compute $\sqrt{\sum_i (a_i - b_i)^2}$ with built-in numerical overflow/underflow scaling.
Basic Example
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 6.0, 3.0])
# 1. Recommended (cleanest, numerically stable, BLAS-backed):
dist = np.linalg.norm(a - b)
print(dist)
# Output: 5.0
# 2. Batch row-wise distances between N pairs of vectors (shape: (N, D)):
A = np.array([[0.0, 0.0], [1.0, 2.0], [3.0, 4.0]])
B = np.array([[3.0, 4.0], [1.0, 2.0], [0.0, 0.0]])
row_dists = np.linalg.norm(A - B, axis=1)
print(row_dists)
# Output: [5. 0. 5.]
Key Details & Edge Cases
- Always pass
axis=1(oraxis=-1) when computing row-wise distances on 2D arrays:- Calling
np.linalg.norm(A - B)withoutaxis=computes the Frobenius norm across the entire 2D matrix (returning a single scalar $\sqrt{\sum_{i,j}(A_{ij} - B_{ij})^2}$) rather than one distance per row! Always specifyaxis=-1for batches of vectors.
- Calling
- Avoid Python lists (
[1, 2] - [3, 4]raisesTypeError):- Subtracting two raw Python
listobjects raisesTypeError: unsupported operand type(s) for -: 'list' and 'list'. Convert inputs withnp.asarray(a, dtype=float)first if inputs might be lists or tuples.
- Subtracting two raw Python
- Integer overflow trap with manual
np.sqrt(np.sum((a - b) ** 2)):- On
int8,int16, orint32arrays, squaring large differences via(a - b) ** 2wraps around silently (int32overflows past $\pm 2.14 \times 10^9$), producingnanor wrong distances—whereasnp.linalg.norm(a - b)automatically promotes integers tofloat64and avoids intermediate overflow.
- On
- All-pairs pairwise distance matrix (
scipy.spatial.distance.cdistvs. broadcasting):- To compute every pairwise distance between matrix
X(M, D)and matrixY(N, D)into an(M, N)matrix:- Best for large matrices:
from scipy.spatial.distance import cdist; dist_matrix = cdist(X, Y, metric="euclidean")(fast C loop without allocating an(M, N, D)intermediate array). - Pure NumPy:
np.linalg.norm(X[:, None, :] - Y[None, :, :], axis=-1)(clean for small/medium arrays, but uses $O(M \cdot N \cdot D)$ RAM).
- Best for large matrices:
- To compute every pairwise distance between matrix
- Skip
np.sqrt()when only comparing relative distances (nearest-neighbor search):- Because $\sqrt{x}$ is strictly monotonic for $x \ge 0$, comparing squared Euclidean distances via
diff = a - b; sq_dist = np.dot(diff, diff)(ornp.einsum("ij,ij->i", diff, diff)for 2D batches) avoids the square-root overhead and runs 2–4× faster in tight inner loops.
- Because $\sqrt{x}$ is strictly monotonic for $x \ge 0$, comparing squared Euclidean distances via
Comparison of Euclidean Distance Methods in NumPy & SciPy
| Method | Syntax | 2D Batch Support ((N, D)) |
Overflow Safe on int Arrays? |
Best Used When |
|---|---|---|---|---|
np.linalg.norm(a - b) (Recommended) |
np.linalg.norm(a - b, axis=-1) |
Yes (axis=-1) |
Yes (auto-casts to float) | General-purpose 1D vector or 2D batch row-wise Euclidean distance. |
Squared Distance (np.dot / einsum) |
d = a - b; np.dot(d, d) |
Yes (np.einsum("ij,ij->i", d, d)) |
Cast to float64 first |
Nearest-neighbor ranking or clustering where exact $\sqrt{\cdot}$ scale isn’t needed. |
np.sqrt(np.sum((a - b) ** 2)) |
np.sqrt(np.sum((a - b) ** 2, axis=-1)) |
Yes (axis=-1) |
No (risks int32 wrap-around) |
Teaching/explicit formula code on pre-validated floating-point arrays. |
scipy.spatial.distance.cdist |
cdist(X, Y, metric="euclidean") |
Yes (all (M, N) pairs) |
Yes | Computing full pairwise distance matrices between two large sets of vectors. |
You must log in or register to comment.
