Doing operation to Equality objects in Sympy

Viewed 28

Is there a way to do some operation to both sides of an equality object in sympy? For example is there a better way to do the following because it is annoying

eq1 = sym.Eq(2*x,5)
eq1 = sym.Eq(2* eq1.rhs, 2 * eq1.lhs)

I would think its like eq1 * 2 but that does not work

1 Answers

The functionality you are looking for is implemented on an external package, Algebra with SymPy. You can install it with pip install -U Algebra-with-SymPy. Then, you can follow the documentation to learn all its feature. Instead of Equality it uses Equation.

Here are a couple of examples:

from sympy import *
from algebra_with_sympy import *
var('a b c x')

# NOTE: Eqn is an alias for Equation
eq1=Eqn(a, b / c)
print(eq1)
# out: a = b/c          (eq1)
print(eq1 * c)
# out: a*c = b
print(c * eq1)
# out: a*c = b
print(exp(eq1))
# out: exp(a) = exp(b/c)
print(exp(log(eq1)))
# out: a = b/c          (eq1)

eq2 = Eqn(b / c + 2, x)
print(eq2)
# out: b/c + 2 = x          (eq2)
eq3 = eq2 - 2
print(eq3)
# out: b/c = x - 2          (eq3)
eq4 = eq1.subs(eq3)
print(eq4)
# out: a = x - 2          (eq4)
print(solve(eq4, x)[0])
# print: x = a + 2

The beautiful thing about this package is that you should be able to apply SymPy's functionalities on equations. Above you can see that:

  • exp(eq1) the exponential function gets applied to both side of the equation.
  • solve is able to return objects of type Equation
  • the usual SymPy's expression manipulation functions (simplify, collect, ...) also works with Equation.
Related