0

I am puzzled about why the following code produces False in sympy, Python

import sympy
from sympy import MatrixSymbol, Trace

A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)

Trace(A*B)==Trace(B*A)

while it is well-known that Tr(AB)=Tr(BA) https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Trace_of_a_product

Any help is appreciated!

Lance
  • 125
  • 1
  • 7
  • 5
    That's because `==` checks for exact structural equality not equality in the mathematical sense. See https://stackoverflow.com/questions/37112738/sympy-comparing-expressions – Lukas S Jun 30 '21 at 15:11
  • @user2640045 Thanks, that actually solves it – Lance Jun 30 '21 at 15:28
  • @user2640045 I just tried `simplify(Trace(B*A)-Trace(A*B))==0` and it still gives me `False`. Do you know why that might be? – Lance Jul 01 '21 at 08:58
  • 1
    Have you looked at the result of `simplify(Trace(B*A)-Trace(A*B))`? I would guess that sympy failed to simplify that. – Lukas S Jul 01 '21 at 12:23
  • Yeah, `simplify(Trace(B*A)-Trace(A*B))` gave me `Trace(B*A)-Trace(A*B)`. Thanks for your answer! – Lance Jul 01 '21 at 14:09

1 Answers1

0

Alright I see you're not happy with letting it go. Here is how you actually get sympy to calculate that for you

from sympy import shape, Matrix, symbols, trace
import numpy as np
from itertools import product

A = Matrix(np.array(symbols([f"a_{i}{j}" for i,j in product(range(1,4),range(1,4))])).reshape(3,3))
B = Matrix(np.array(symbols([f"b_{i}{j}" for i,j in product(range(1,4),range(1,4))])).reshape(3,3))
trace(A*B)-trace(B*A) == 0

Which finally gives you True.

Lukas S
  • 3,212
  • 2
  • 13
  • 25