6

I have a relatively simple complex sympy expression which one can easily read the coefficients off of the variables. However coeff function does not appear to be working correctly

import sympy as sp

a,b =  sp.symbols("a, b")

expr = 2640.0*a  - 4.5*(1 + 1j)*(264.0*a + 264.0*b) - 4.5*(+1 - 1j)*(264.0*a  + 264.0*b)

print(expr.coeff(a))

> 2640.00000000000

print(sp.simplify(expr))

> 264.0*a - 2376.0*b

I would expect the output of expr.coeff(a) to return 264.0 but it clearly isnt? Any help is appreciated.

shaun252
  • 61
  • 4

2 Answers2

2

coeff gives coefficients of the expression at the top level. If you use expand before looking for the coefficient then you will get the mathematical (not expression-dependent-literal) coefficient. If you know the expression is linear in the symbol of interest, you could also differentiate once:

>>> expr.diff(a)
264.000000000000
>>> expr.expand().coeff(a)
264.000000000000

Poly automatically expands expressions and allows queries for monomials, too:

>>> Poly(expr).coeff_monomial(a)
264.000000000000
smichr
  • 16,948
  • 2
  • 27
  • 34
0

Your first expression has 2640.0 as the coefficient of a. As you can see, the coefficient becomes zero only after simplifying it. Indeed, if you print the coefficient after simplifying the expression, you get 264.0

import sympy as sp

a,b =  sp.symbols("a, b")

expr = 2640.0*a  - 4.5*(1 + 1j)*(264.0*a + 264.0*b) - 4.5*(+1 - 1j)*(264.0*a  + 264.0*b)

print(expr.coeff(a))
# 2640.00000000000

print(sp.simplify(expr))
# 264.0*a - 2376.0*b

print(sp.simplify(expr).coeff(a)) # <--- Simplified expression
# 264.000000000000
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • I am aware of how it works after simplifying but the statement "Your first expression has 2640.0 as the coefficient of a" is not true. The coefficient of a variable is only defined once you have simplified to having one instance of that variable in the expression. There is no reason why it only selects the first instance of "a" in my first expression and returns the coefficient. – shaun252 Apr 04 '19 at 04:55