# Manually grouping symbolic terms

Given a symbolic expression like:

sage: var("a b c x y")
(a, b, c, x, y)
sage: a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x


How can I manually collect terms together? I want to represent this equation in the form:

$$Ax^2 + Bxy + Cy^2$$

Where $A = a, B = 2a + b, C = a + b + c$. Desired output should be:

a*x^2 + (2*a + b)*x*y + (a + b + c)*y^2


And then is there any way to read off these coefficients? Thanks

edit retag close merge delete

it is too bad that sage can't collect on more than one variable. In Mathematica one can just type expr = a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x; Collect[expr, {x, y}] and get a x^2+(2 a+b) x y+(a+b+c) y^2

Sort by » oldest newest most voted

Does this :

sage: var("a b c x y")
(a, b, c, x, y)
sage: foo =  a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x
sage: sum([u*foo.coefficient(u) for u in (x^2, y^2, x*y)])
a*x^2 + (2*a + b)*x*y + (a + b + c)*y^2


HTH,

more

One way is:

R.<x,y>=SR[]
a,b,c=var('a b c')
p=a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x
p
a*x^2 + (2*a + b)*x*y + (a + b + c)*y^2

p.coefficients()
[a, 2*a + b, a + b + c]

more

Using true polynomials, separating variables, we can ask for coefficients of involved monomials...

R.<a,b,c> = PolynomialRing(QQ)
S.<x,y> = PolynomialRing(R)

f = a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x


And now:

for entry in f:    print(entry)


gives:

sage:     for entry in f:    print(entry)
....:
(a, x^2)
(2*a + b, x*y)
(a + b + c, y^2)


So each entry collects the corresponding monomial in $x,y$ in its last component, the first component being the coefficient.

more

Variant not needing explicit construction of both rings :

sage: var("a, b, c, y")
(a, b, c, y)
sage: f = a*x^2 + a*y^2 + b*y^2 + c*y^2 + (2*a*y + b*y)*x
sage: F=sum([u*u for u in f.polynomial(ring=PolynomialRing(SR,[x, y]))]) ; F
a*x^2 + (2*a + b)*x*y + (a + b + c)*y^2


But beware :

sage: F.parent()
Multivariate Polynomial Ring in x, y over Symbolic Ring


You can get back to SR with this awful trick :

sage: SR(str(F)).parent()
Symbolic Ring


HTH,