Integer distance calculations overflow before reduction
Author: Afloat16Created Sep 29, 2026Updated Sep 29, 2026
Problem and proposed change
Subtracting and squaring integer arrays in their original dtype can wrap around and produce incorrect distances. Subtract integer arrays exactly before converting the differences to floating point; converting the operands first can lose differences between adjacent int64 values.
Reproduction
import numpy as np
from numpy_ml.utils.distance_metrics import euclidean, manhattan
x = np.array([0], dtype=np.uint8)
y = np.array([255], dtype=np.uint8)
print(euclidean(x, y), manhattan(x, y))
# Expected: 255.0, 255.0Validation
Source: numpy_ml/utils/distance_metrics.py, Git blob 8c51e6c74db61649e389e7ac785b1c3b2df053fe; rechecked against current upstream. Focused before/after tests were rerun for this submission.
Complete standalone source module loaded with real dependencies; selected utility behaviors tested. Not the full project suite.
Before: 12 failed, 9 passed, 5 warnings in 0.12s
After: 21 passed, 5 warnings in 0.08s
Candidate patch
--- a/numpy_ml/utils/distance_metrics.py
+++ b/numpy_ml/utils/distance_metrics.py
@@ -1,4 +1,12 @@
import numpy as np
+
+
+def _difference(x, y):
+ # Subtract integers exactly before converting the distance to floating point.
+ if x.dtype.kind in "uib" and y.dtype.kind in "uib":
+ return np.asarray(x.astype(object) - y.astype(object), dtype=np.float64)
+ dtype = np.result_type(x.dtype, y.dtype, np.float64)
+ return x.astype(dtype, copy=False) - y.astype(dtype, copy=False)
def euclidean(x, y):
@@ -23,7 +31,7 @@
d : float
The L2 distance between **x** and **y**.
"""
- return np.sqrt(np.sum((x - y) ** 2))
+ return np.sqrt(np.sum((_difference(x, y)) ** 2))
def manhattan(x, y):
@@ -48,7 +56,7 @@
d : float
The L1 distance between **x** and **y**.
"""
- return np.sum(np.abs(x - y))
+ return np.sum(np.abs(_difference(x, y)))
def chebyshev(x, y):
@@ -73,7 +81,7 @@
d : float
The Chebyshev distance between **x** and **y**.
"""
- return np.max(np.abs(x - y))
+ return np.max(np.abs(_difference(x, y)))
def minkowski(x, y, p):
@@ -103,7 +111,7 @@
d : float
The Minkowski-`p` distance between **x** and **y**.
"""
- return np.sum(np.abs(x - y) ** p) ** (1 / p)
+ return np.sum(np.abs(_difference(x, y)) ** p) ** (1 / p)
def hamming(x, y):Source: ddbourgin/numpy-ml