Skip to content

numpy/inv-then-multiply

Rule inv-then-multiply
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

Multiplying by an inverse loses more digits than solving, and was 3.8 times slower. Call np.linalg.solve(a, b).

beta = np.linalg.inv(X.T @ X) @ X.T @ y
beta = np.linalg.solve(X.T @ X, X.T @ y)

The rule reports np.linalg.inv(a) @ b, np.linalg.inv(a).dot(b), np.dot(np.linalg.inv(a), b) and np.linalg.inv(a) @ b @ c, as in the normal equations.

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.solve(a, b), np.linalg.solve(a, b @ c).

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

Multiplying by the inverse loses more digits than solving, and solve ran 3.8 times faster for a vector on a 1,000 by 1,000 matrix. Write $NP.linalg.solve($A, $B).

Browse the other rules of the NumPy pack.