Search code examples
pythonsympysymbolic-math

sympy: Expr.coeff() return 0 if the expression is over a denominator


When I try to get the coefficient of x in an expression like x + 2 it is 1 but when I divide by y, the coefficient is 0 and I don't understand why:

>>> from sympy import *
>>> from sympy.abc import x, y
>>> eq = x + 2
>>> eq.coeff(x)
1
>>> (eq/y).coeff(x)
0

Solution

  • If you read the docstring for Expr.coeff it mentions

        In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
        from the following:
        
        >>> (x + z*(x + x*y)).coeff(x)
        1
    

    So it is very literally checking the factors of the terms of the expression as written for the factor of interest. In x + 2 there are two terms and one has x as a factor. In (x + 2)/y there is only one term having factors of x+2 and 1/y -- there is no factor of x so the coefficient is 0. If you use expand on the expression you will get what you are looking for.

    >>> expand((x + 2)/y).coeff(x)
    1/y