Compute a table containing the squared Euclidean distance from every point to every center.
Problem
Input. Float64 arrays points with shape (n, d) and centers with shape (k, d).
Output. Return an (n, k) array whose entry [i, j] is the sum of squared coordinate differences.
Do not take a square root: these are squared distances, not Euclidean distances themselves.
Rules. Feature counts must match. Repeated points and empty axes are allowed; preserve both inputs. Differences, squares, and sums must remain representable in float64. Integer inputs are outside this numeric contract because they may overflow before reduction.
Example. Points [[0, 0], [1, 2]] and centers [[0, 0], [1, 0]] return [[0, 1], [5, 4]].
The lower-right entry is 0 * 0 + 2 * 2 = 4.
Picture
For points (0,0), (1,2) and centers (1,0), (2,2), the output is [[1,8],[4,1]].
Inserted axes form (n,1,d) and (1,k,d) views.
Their difference has shape (n,k,d); summing only the feature axis retains both ownership axes.
Problem trace
Separate point pair: squared displacement survives a common translation
Reference drawing
Problem trace
Sum squared coordinate differences; do not take a square root
Execution trace
- columns
- C0 (1,0), C1 (2,2)
- shape
- pair grid [n=2,k=2]
- C / row 0
- P0 (0,0)
- pair P0,C0
- not shown→(0, 0)
- shape
- pair grid [n=2,k=2]→differences [2,2,2]
- columns
- C0 (1,0), C1 (2,2)→not shown
- 4,4
- not shown→(0, 1)
- pair P0,C0
- (0, 0)→not shown
- operation
- not shown→elementwise square
- distance
- not shown→(1, 1)
- 4,4
- (0, 1)→not shown
- arithmetic
- not shown→sum over final axis d
- Recognize it
- Use it when every item in one batch must pair with every item in another batch and the per-pair calculation is identical across a shared feature dimension.
- Keep true
- Cell [i,j,:] always belongs to point i and center j; broadcasting changes alignment, not values, and reducing only the final feature axis preserves the pair grid.
- Reuse it
- For all-pairs tensor operations, insert singleton axes where each operand should repeat, verify the broadcasted axis meaning, and reduce only the intended feature axes.
Without singleton axes, subtraction may fail or compare corresponding rows instead of every point-center pair.
Code
import numpy as np
def pairwise_squared_distances(
points: np.ndarray, centers: np.ndarray
) -> np.ndarray:
differences = points[:, None, :] - centers[None, :, :]
return np.sum(differences * differences, axis=-1)
Cost: time and temporary space.
The retained output additionally occupies space, including when the feature axis is empty.
Change the Requirement
Bound Pairwise Temporary Storage
New task: Emit point-row blocks rather than retaining every pairwise difference.
Picture and change: Keep center ownership fixed; restrict the active point axis to block_size.
Code: The reference still computes each complete block.
def squared_distance_blocks(points, centers, block_size: int):
if block_size <= 0:
raise ValueError("block_size must be positive")
for start in range(0, len(points), block_size):
yield start, pairwise_squared_distances(points[start:start + block_size], centers)
Check: Two point rows with block size one yield offsets 0,1 and rows [1,8], [4,1].
Use when: The consumer processes blocks; retaining them all still costs output storage.
Avoid the Three-Axis Difference
New task: Compute distances through norms and matrix multiplication.
Picture and change: Expand .
Code: Retain float64 shapes; require representable norm and product intermediates.
def squared_distances_gram(points, centers):
point_norms = np.einsum("nd,nd->n", points, points)[:, None]
center_norms = np.einsum("kd,kd->k", centers, centers)[None, :]
result = point_norms + center_norms - 2 * (points @ centers.T)
return np.maximum(result, 0.0)
Check: The small example still gives [[1,8],[4,1]].
Use when: Explicit array storage must scale as , excluding backend workspace. Cancellation can destroy small distances; clipping negatives does not restore lost accuracy.
Reconstruct
Why can the Gram expression return zero for distinct points?
Reasoned answer
In float64, point [[100000001.0]] and center [[100000000.0]] have direct squared distance 1.
The Gram form subtracts nearly equal values around and returns 0 for this example.
Subtracting nearby coordinates before squaring avoids that particular cancellation, but neither formulation prevents every overflow or rounding problem.
Check representative magnitudes rather than treating algebraic equivalence as identical floating-point behavior.
The blocked version needs pairwise temporary storage and corresponding block-output storage. It does not reduce total arithmetic or automatically make the consumer streaming.