# Show correct output of polynomial Anonymous

Hi, I am new to sage and I am trying to construct a polynomial to try to transform it. However, when writing it I am getting an incorrect output.

x=var("x") s = (x^2+2x+1) + 1/(x^2+2x+1) s.show()

And this is the output I am getting -

x^2+2x + 1/x^2+2x+1 +1 (I am unsure why the 1 is carrying over all the way to right side)

I am looking to obtain the following output to begin transforming it -

x^2+2x+1 + 1/x^2+2x+1

Appreciate any help!

edit retag close merge delete

This is a rational function, and an 'ordering of terms' is not part of the data, so Sage should not be expected to preserve it. Nevertheless the desired output can be obtained; see my answer.

I tried using the QQ command received the following:

R.<x> = QQ[]

s = (x^2 + 2x + 1) + 1/(x^2 + 2x + 1)

print s

output-

(x^4 + 4x^3 + 6x^2 + 4x + 2)/(x^2 + 2x + 1)

Do you know why the polynomial is expanding?

That is due to the implementation of fraction field elements. To render the expression in the desired way, see my answer.

Sort by » oldest newest most voted The object you want to construct is a rational function (quotient of polynomials), and we can define it as such:

R.<x> = QQ[]
s = (x^2 + 2*x + 1) + 1/(x^2 + 2*x + 1)


We can obtain the two parts you want e.g. as follows (or you could have defined them individually):

sage: q, r = s.numerator().quo_rem(s.denominator())
sage: parts = (q, r/s.denominator())
sage: parts
(x^2 + 2*x + 1, 1/(x^2 + 2*x + 1))


Now we can generate the LaTeX for each part individually and join them by a plus symbol:

sage: latex_code = latex(parts) + '+' + latex(parts)
sage: latex_code
x^{2} + 2 x + 1 + \frac{1}{x^{2} + 2 x + 1}
sage: show(latex_code)


Showing the LaTeX gives the desired output: $x^{2} + 2 x + 1 + \frac{1}{x^{2} + 2 x + 1}$.

more