Reputation: 155
I am using the sympy library for python3, and I am handling equations, such as the following one:
a, b = symbols('a b', positive = True)
my_equation = Eq((2 * a + b) * (a - b) / 2, 0)
my_equations
gets printed exactly as I have defined it ((2 * a + b) * (a - b) / 2 == 0
, that is), and I am unable to reduce it even using simplify
or similar functions.
What I am trying to achieve is simplifying the nonzero factors from the equation (2 * a + b
and 1 / 2
); ideally, I'd want to be able to simplify a - b
as well, if I am sure that a != b
.
Is there any way I can reach this goal?
Upvotes: 1
Views: 416
Reputation: 1957
The point is that simplify() is not capable (yet) of complex reasoning about assumptions. I tested it on Wolfram Mathematica's simplify, and it works. It looks like it's a missing feature in SymPy.
Anyway, I propose a function to do what you're looking for.
Define this function:
def simplify_eq_with_assumptions(eq):
assert eq.rhs == 0 # assert that right-hand side is zero
assert type(eq.lhs) == Mul # assert that left-hand side is a multipl.
newargs = [] # define a list of new multiplication factors.
for arg in eq.lhs.args:
if arg.is_positive:
continue # arg is positive, let's skip it.
newargs.append(arg)
# rebuild the equality with the new arguments:
return Eq(eq.lhs.func(*newargs), 0)
Now you can call:
In [5]: simplify_eq_with_assumptions(my_equation)
Out[5]: a - b = 0
You can easily adapt this function to your needs. Hopefully, in some future version of SymPy it will be sufficient to call simplify.
Upvotes: 1