How to get constant of expression?

20 views
Skip to first unread message

Kevin Hunter

unread,
Jan 9, 2012, 2:48:58 AM1/9/12
to sy...@googlegroups.com
Hullo Sympy Group,

I have a series of relations that I am receiving from an outside object and code base.  These equations are in no particular format, and I want to convert them to one.  At the moment, the end format I need is

format:  lhs_expression   [op]  constant
example: 3x + 4y <= 7

I have code that currently looks like this:

-----
lhs, rhs = rel.lhs, rel.rhs
lhs -= rhs
rhs = 0

possible_constant = lhs.as_ordered_terms()[ -1 ]
if possible_constant.is_real:
lhs -= possible_constant
rhs -= possible_constant
new_relation = type(rel)(lhs, rhs)
-----

Given that Sympy has already parsed the lhs expression, is there a more efficient/cleaner method of getting its constant?  Something perhaps like:

-----
lhs, rhs = rel.lhs, rel.rhs
lhs -= rhs
rhs = -lhs.constant_term
lhs -= rhs
new_relation = type(rel)(lhs, rhs)
-----

Thanks,

Kevin

Chris Smith

unread,
Jan 9, 2012, 3:05:20 AM1/9/12
to sy...@googlegroups.com
The as_coeff_Add method is probably what you want:

>>> (x+y).as_coeff_Add()
(0, x + y)
>>> (x+y+3).as_coeff_Add()
(3, x + y)
>>> (3*x).as_coeff_Add()
(0, 3*x)
>>> (x+y+3.0).as_coeff_Add()
(3.00000000000000, x + y)

/c

Chris Smith

unread,
Jan 9, 2012, 5:39:42 AM1/9/12
to sy...@googlegroups.com
On Mon, Jan 9, 2012 at 1:33 PM, Kevin Hunter <hun...@gmail.com> wrote:
Hullo Sympy Group,

I have a series of relations that I am receiving from an outside object and code base.  These equations are in no particular format, and I want to convert them to one.  At the moment, the end format I need is


In case there is any nesting of your expressions, you might want to apply `expand_mul(expand_multinomial(eq.lhs - eq.rhs))` to make sure the expression is flat:

>>> eq
3*x*(x + y) == -x + 3
>>> expand_mul(expand_multinomial(eq.lhs - eq.rhs)).as_coeff_Add()
(-3, 3*x**2 + 3*x*y + x)
>>> Eq(_[1], -_[0])
3*x**2 + 3*x*y + x == 3


Kevin Hunter

unread,
Jan 9, 2012, 10:45:20 AM1/9/12
to sy...@googlegroups.com
Thank you.
Reply all
Reply to author
Forward
0 new messages