Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
shaun252 Avatar asked Nov 07 '22 19:11

shaun252


1 Answers

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
like image 88
smichr Avatar answered Nov 15 '22 11:11

smichr