dariober
dariober

Reputation: 9062

sympy: How to get zero for absent constant term

On SymPy 0.7.5 (Python 2.7.8-64-bit). I'm unable to get the constant term from an expression when the constant term is zero or absent (an absent constant is the same of a zero constant, right?).

I can get the constant term from an expression with expr.coeff(x, 0). E.g.:

isympy ## Load sympy etc...

(x + 3).coeff(x, 0)        #-> 3 ok
(x).coeff(x, 0)            #-> 0 ok
(4*x**2 + 3*x).coeff(x, 0) #-> 0 ok

Now, how can I get 0 in these cases?

(4*x).coeff(x, 0)     #-> 4 
(4*x**2).coeff(x, 0)  #-> 4 why not 0?!

I'm sure this has been asked & documented before but I can't find the answer at least without some awkward workaround. Thanks Dario

Edit Full output from interactive session:

python
Python 2.7.8 (default, Sep 14 2014, 18:20:38) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import sympy
>>> 
>>> x= sympy.symbols('x')
>>> (4*x).coeff(x, 0)
4
>>> sympy.__version__
'0.7.5'

Upvotes: 5

Views: 654

Answers (2)

nanren888
nanren888

Reputation: 1

Just to note, from memory, quite compatibly, something like (4*x + 3*y + 7).coeff(x, 0) gives 3*y + 7 . Have yet to discover an elegant way to get the constant term.

Upvotes: 0

dariober
dariober

Reputation: 9062

Solution: Upgrade to sympy 0.7.6. Unless I was doing something silly it appears this was a bug 0.7.5.

python
Python 2.7.8 (default, Sep 14 2014, 18:20:38) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sympy
>>> x= sympy.symbols('x')
>>> (4*x).coeff(x, 0)
0
>>> sympy.__version__
'0.7.6'

Upvotes: 1

Related Questions