RuRo
RuRo

Reputation: 379

Sympy comparing expressions after evaluation

I want a function that will compare, whether evaluated and non-evaluated expressions are different. So this:

import sympy.parsing.sympy_parser as spp

string = "x+x"
exp1 = spp.parse_expr(string, evaluate = False)
exp2 = spp.parse_expr(string)
print exp1
print exp2
print exp1 == exp2

Should output

x + x
2*x
False

And the same code with string = "x**2+1" should output

x**2+1
x**2+1
True # But it outputs False here too.

Yes, I have read the FAQ, but it doesn't explain how to fix/work around this.

Upvotes: 0

Views: 178

Answers (1)

li.davidm
li.davidm

Reputation: 12116

The relevant issue is https://github.com/sympy/sympy/issues/5904.

When evaluate=False, the args property is not sorted:

>>> a = sympify('x**2 + 1', evaluate=False)
>>> b = sympify('x**2 + 1')
>>> a == b
False
>>> a.args
(x**2, 1)
>>> b.args
(1, x**2)

I don't believe (but you should check on the mailing list to be sure) that there is a built-in way to resolve this. The best approach depends on what you are trying to accomplish with this comparison.

The discussion at https://groups.google.com/forum/#!msg/sympy/LU5DQGJJhfc/_Le_u8UGtx0J (though outdated!) suggests making a custom comparison function, perhaps using the _sorted_args property:

>>> a._sorted_args
[1, x**2]
>>> b._sorted_args
[1, x**2]

Upvotes: 1

Related Questions