Skip to content

numpy/norm-by-hand

Rule norm-by-hand
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

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).

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

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).

Browse the other rules of the NumPy pack.