# Turning an expression into a multivariate polynomial?

Suppose I have the expression

-a^3x^2 - a^2xy^2 + axy + bx^2 + 2bxy + xy^2


I want to turn this into a polynomial in x and y:

(1-a^2)xy^2+(a+2*b)xy+(b-a^3)x^2


so that I can then extract the coefficients (by setting x=1, y=1 in the list of operands of the new expression). How do I tell Sage which of the four variables will be the polynomial variables?

edit retag close merge delete

Sort by » oldest newest most voted

If you just want to evaluate your symbolic expression by setting x=1, y=1, you can directly do:

sage: f(x=1,y=1)
-a^3 - a^2 + a + 3*b + 1


Otherwise, you can try:

sage: R.<x,y> = PolynomialRing(SR,2) ; R
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: var('a,b')
sage: P = -a^3*x^2 - a^2*x*y^2 + a*x*y + b*x^2 + 2*b*x*y + x*y^2
sage: P.parent()
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: P(1,1)
-a^3 - a^2 + a + 3*b + 1


But you should notice that x and y are not symbolic expression, and are declared as polynomials before P is defined.

If the symbolic function is given as a symbolic expression and you want to make it a polynomial afterwards, the best way i found is to tranform it first as a polynomial in 4 variables, and then set a and b back to the Symbolic Ring:

sage: var('a,b,x,y')
(a, b, x, y)
sage: f = -a^3*x^2 - a^2*x*y^2 + a*x*y + b*x^2 + 2*b*x*y + x*y^2
sage: P = f.polynomial(QQ)
sage: P.parent()
Multivariate Polynomial Ring in a, b, x, y over Rational Field
sage: R.<x,y> = PolynomialRing(SR,2) ; R
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: Q = P(var(a),var(b),x,y)
sage: Q.parent()
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: Q
(-a^2 + 1)*x*y^2 + (-a^3 + b)*x^2 + (a + 2*b)*x*y
sage: Q(1,1)
-a^3 - a^2 + a + 3*b + 1

more