As I understand it, str converts a SymPy expression into a string and sympify converts a string into a SymPy expression. Thus, I would expect the following to hold (for reasonable expressions).
>>> sy.sympify(str(expr)) == expr
True
I tried this and indeed this is the case for simple examples (e.g., expr = x+y). However, when I tried it with the following expression, it did not work:
import sympy as sy
a = sy.symbols("a")
A = sy.Matrix(3,3, a)
c0,c1,c2 = sy.symbols("c0 c1 c2", positive = True)
c1*c2**2*a(0, 1)**2*a(1, 2)*a(2, 2) - c1*c2**2*a(0, 1)**2*a(2, 2)**2 - c1*c2**2*a(0, 1)*a(0, 2)*a(1, 1)*a(2, 2) + c1*c2**2*a(0, 1)*a(0, 2)*a(2, 1)*a(2, 2) - c1*c2**2*a(0, 1)*a(1, 1)*a(1, 2)*a(2, 2) + c1*c2**2*a(0, 1)*a(1, 1)*a(2, 2)**2 + c1*c2**2*a(0, 2)*a(1, 1)**2*a(2, 2) - c1*c2**2*a(0, 2)*a(1, 1)*a(2, 1)*a(2, 2) - c1*a(0, 0)**2*a(1, 1)*a(2, 1) + c1*a(0, 0)**2*a(2, 1)**2 + c1*a(0, 0)*a(0, 1)*a(1, 1)*a(2, 0) - c1*a(0, 0)*a(0, 1)*a(2, 0)*a(2, 1) + c1*a(0, 0)*a(1, 0)*a(1, 1)*a(2, 1) - c1*a(0, 0)*a(1, 0)*a(2, 1)**2 - c1*a(0, 0)*a(1, 1)**2*a(2, 0) + c1*a(0, 0)*a(1, 1)*a(2, 0)*a(2, 1) - c2**2*a(0, 0)*a(0, 1)*a(1, 2)*a(2, 2) + c2**2*a(0, 0)*a(0, 1)*a(2, 2)**2 + c2**2*a(0, 0)*a(0, 2)*a(1, 1)*a(2, 2) - c2**2*a(0, 0)*a(0, 2)*a(2, 1)*a(2, 2) + c2**2*a(0, 1)*a(1, 0)*a(1, 2)*a(2, 2) - c2**2*a(0, 1)*a(1, 0)*a(2, 2)**2 - c2**2*a(0, 2)*a(1, 0)*a(1, 1)*a(2, 2) + c2**2*a(0, 2)*a(1, 0)*a(2, 1)*a(2, 2) + c2*a(0, 0)**2*a(1, 2)*a(2, 1) - c2*a(0, 0)**2*a(2, 1)*a(2, 2) - c2*a(0, 0)*a(0, 1)*a(1, 2)*a(2, 0) + c2*a(0, 0)*a(0, 1)*a(2, 0)*a(2, 2) - c2*a(0, 0)*a(1, 0)*a(1, 2)*a(2, 1) + c2*a(0, 0)*a(1, 0)*a(2, 1)*a(2, 2) + c2*a(0, 0)*a(1, 1)*a(1, 2)*a(2, 0) - c2*a(0, 0)*a(1, 1)*a(2, 0)*a(2, 2)
Can somebody tell me why it doesn't work for this expression?
PS: I know I'm supposed to put a minimal working example, but I just didn't find which part of the expression is causing the problem.
A minimal example would be
x = sy.symbols("x", positive=True)
expr = 2*x
sy.sympify(str(expr)) == expr # False
Which makes perfect sense: the string representation of expr, namely "2*x", has no information about x being positive. Accordingly, sy.sympify(str(expr)) creates a new symbol with a name "x" and with default assumptions. This is a different symbol from the original one.
Without the positivity assumption, the comparison would return True.
A way to keep the positivity assumption is to say explicitly that the character "x" in the string means the existing symbol x, by using the locals dictionary:
x = sy.symbols("x", positive=True)
expr = 2*x
sy.sympify(str(expr), locals={"x": x}) == expr # True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With