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)What the rule reports
Section titled “What the rule reports”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()).
How to fix it
Section titled “How to fix it”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.
Diagnostic message
Section titled “Diagnostic message”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.