sympy / sympy

A computer algebra system written in pure Python
https://sympy.org/
Other
12.78k stars 4.39k forks source link

Wrong result of the inverse matrix with non-commutative elements #26194

Open naruo-ohga opened 7 months ago

naruo-ohga commented 7 months ago

Hi, I have recently encountered an issue in calculating the inverse matrix with non-commutative elements:

A, C, D = sympy.symbols('A C D', commutative=False)
X = sympy.Matrix([[A, C], [C, D]])
Xinv = X.inv()

print(sympy.simplify(Xinv))
print(sympy.simplify(X*Xinv - sympy.eye(2))) # should be zero
print(sympy.simplify(Xinv*X - sympy.eye(2))) # should be zero

This returns

Matrix([[2*A*C*(2*A*C*A - A**2*C - C*A**2)**(-1) - C*A*(2*A*C*A - A**2*C - C*A**2)**(-1), -A**2*(2*A*C*A - A**2*C - C*A**2)**(-1)], [-C*(A*C - C*A)**(-1), A*(A*C - C*A)**(-1)]])
Matrix([[-1 + A*(2*A*C - C*A)*(2*A*C*A - A**2*C - C*A**2)**(-1) - C**2*(A*C - C*A)**(-1), -A**3*(2*A*C*A - A**2*C - C*A**2)**(-1) + C*A*(A*C - C*A)**(-1)], [C*(2*A*C - C*A)*(2*A*C*A - A**2*C - C*A**2)**(-1) - D*C*(A*C - C*A)**(-1), -1 - C*A**2*(2*A*C*A - A**2*C - C*A**2)**(-1) + D*A*(A*C - C*A)**(-1)]])
Matrix([[-1 - A**2*(2*A*C*A - A**2*C - C*A**2)**(-1)*C + (2*A*C - C*A)*(2*A*C*A - A**2*C - C*A**2)**(-1)*A, -A**2*(2*A*C*A - A**2*C - C*A**2)**(-1)*D + (2*A*C - C*A)*(2*A*C*A - A**2*C - C*A**2)**(-1)*C], [A*(A*C - C*A)**(-1)*C - C*(A*C - C*A)**(-1)*A, -1 + A*(A*C - C*A)**(-1)*D - C*(A*C - C*A)**(-1)*C]])

I think the inverse matrix in the first line of the output is wrong because it does not contain D. This is more apparent from the second and third lines, which should be Matrix([[0, 0], [0, 0]]).

I'm wondering if this is a bug, or maybe I'm doing something wrong?

I'm using sympy version 1.12 on python version 3.10.12.

oscarbenjamin commented 7 months ago

I am not sure that the algorithm is intended to be able to handle non-commutative expressions. With current master this gives an error:

PolynomialError: non-commutative expressions are not supported
naruo-ohga commented 7 months ago

So the current master version explicitly raises an error with this input. Thank you for clarifying!