ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 06 Jun 2013 05:40:32 +0200Turning an expression into a multivariate polynomial?https://ask.sagemath.org/question/10198/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?Thu, 06 Jun 2013 00:57:36 +0200https://ask.sagemath.org/question/10198/turning-an-expression-into-a-multivariate-polynomial/Answer by tmonteil for <p>Suppose I have the expression</p>
<pre><code>-a^3x^2 - a^2xy^2 + axy + bx^2 + 2bxy + xy^2
</code></pre>
<p>I want to turn this into a polynomial in x and y:</p>
<pre><code>(1-a^2)xy^2+(a+2*b)xy+(b-a^3)x^2
</code></pre>
<p>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?</p>
https://ask.sagemath.org/question/10198/turning-an-expression-into-a-multivariate-polynomial/?answer=15036#post-id-15036If 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
Thu, 06 Jun 2013 05:40:32 +0200https://ask.sagemath.org/question/10198/turning-an-expression-into-a-multivariate-polynomial/?answer=15036#post-id-15036