Skip to content

numpy/sum-of-products

Rule sum-of-products
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

np.sum(a * b) builds the array of products to add it up, which was 2.4 times slower. Use np.vdot or np.dot.

energy = np.sum(signal ** 2)
energy = np.vdot(signal, signal)

The rule reports np.sum(a * b), np.sum(x ** 2), np.sum(np.square(x)) and np.mean((a - b) ** 2), but not when an operand is a number, a comparison, a conjugate or a new axis.

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.vdot(a, b), np.vdot(x, x). The mean of squared differences has no fix.

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

This builds the array of products to add it up, which ran 2.4 times slower on 1,000,000 values. Write $NP.vdot($A, $B).

Browse the other rules of the NumPy pack.