Skip to content

numpy/norm-by-hand

Pack Severity Fix Versions
NumPy warning unsafe, with xpd check --fix --unsafe-fixes All versions

Building the array of squares to add them up was 3.9 times slower. Call np.linalg.norm.

distance = np.sqrt(np.sum((a - b) ** 2))
distance = np.linalg.norm(a - b)

The rule reports np.sqrt(np.sum(x ** 2)), np.sqrt(np.sum(x * x)), np.sqrt(np.sum(np.square(x))), np.sqrt((x ** 2).sum()) and np.sqrt((x * x).sum()).

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.linalg.norm(x).

The two forms can round differently. For complex numbers the norm squares magnitudes, and it can overflow when squaring large values.

This builds the array of squares to add it up, which ran 3.9 times slower on 1,000,000 values. Write $NP.linalg.norm($X).

See all rules in the NumPy pack.