Processing math: 100%
Ask Your Question
0

Manually grouping symbolic terms

asked 2 years ago

narodnik gravatar image

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:

Ax2+Bxy+Cy2

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

Preview: (hide)

Comments

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

Nasser gravatar imageNasser ( 2 years ago )

3 Answers

Sort by » oldest newest most voted
2

answered 2 years ago

Emmanuel Charpentier gravatar image

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

answer your question ?

HTH,

Preview: (hide)
link
2

answered 2 years ago

achrzesz gravatar image

updated 2 years ago

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]

See also https://ask.sagemath.org/question/101...

Preview: (hide)
link
1

answered 2 years ago

dan_fulea gravatar image

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.

Preview: (hide)
link

Comments

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[0]*u[1] 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,

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2 years ago

Seen: 263 times

Last updated: Feb 06 '23