Skip to content

numpy/sum-of-products

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

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.

vdot conjugates a complex first operand, can reject broadcast operands, and retains integer or bool dtypes where np.sum can widen them. A different accumulation order can change the last bits.

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

See all rules in the NumPy pack.