Hello everyone,

I have been using the method "as_coeff_dictionary" to get fast access to 
the coefficients of simple multi-variable linear polynomials (a*x+b*y+... 
where x,y are symbols and a,b are numerical).

For the most part it works great, but I ran into a couple of quirks with 
this approach. First of all, "as_coeff_dictionary" only treats floating 
point or integer values as coefficients, and any irrational or more 
complicated pure numerical expressions become part of the "variable" 
instead. I can live with this by applying N first, but ideally a method 
that could split off any numerical factors from the true variables would be 
preferable to me.

More insidious than this (at least to my way of looking at it) is that 
passing a Mul object instead of an Add results in things like {<number>*x : 
1} instead of {x:<number>}. I tried working around this using a Poly 
instead, but that only made things worse. I can work around this by adding 
a dummy constant 1 to the mix: (<number>*x+1) -> {1:1,x:<number>}.

I think I now understand why the first issue pops up, but I really don't 
understand the second one - is it a bug or is there a reason for the 
behavior? Also, is there a better way to deal with this simple situation 
that doesn't sacrifice the speed of this method? I really just need a list 
of true variables and a list of their coefficients and assurance they are 
both ordered the same way.

Full test code below.

Thanks!
-David

>>> from sympy import S,N,sqrt,Poly
>>> x,y = S('x'),S('y')
>>> p = 4*sqrt(97)*x/97 - 2*sqrt(85)*y/85
>>> p
4*sqrt(97)*x/97 - 2*sqrt(85)*y/85
>>> N(p)
0.406138466053448*x - 0.216930457818656*y
>>> p.as_coefficients_dict()
defaultdict(<type 'int'>, {sqrt(85)*y: -2/85, sqrt(97)*x: 4/97})
>>> sympy.N(p).as_coefficients_dict()
defaultdict(<type 'int'>, {x: 0.406138466053448, y: -0.216930457818656})
>>> p2 = 0.496138938356834*x
>>> p2
0.496138938356834*x
>>> p2.as_coefficients_dict()
defaultdict(<type 'int'>, {0.496138938356834*x: 1})
>>> (p2+1).as_coefficients_dict()
defaultdict(<type 'int'>, {1: 1, x: 0.496138938356834})
>>> ############################# using Poly's doesn't really change 
anything ###############################
>>> Poly(N(p)).coeffs()
[0.406138466053448, -0.216930457818656]
>>> Poly(p2).coeffs()
[0.496138938356834]
>>> Poly(N(p2)).coeffs()
[0.496138938356834]
>>> Poly(N(p2)).as_coefficients_dict()
defaultdict(<type 'int'>, {Poly(0.496138938356834*x, x, domain='RR'): 1})

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sympy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to