shaun252
shaun252

Reputation: 61

Obtaining coefficients of complex expressions in sympy

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.

Upvotes: 6

Views: 491

Answers (2)

smichr
smichr

Reputation: 19057

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

Upvotes: 2

Sheldore
Sheldore

Reputation: 39052

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

Upvotes: 0

Related Questions