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.Wed, 31 Mar 2021 09:14:19 +0200How to find the degree of a polynomialhttps://ask.sagemath.org/question/56440/how-to-find-the-degree-of-a-polynomial/ Is there a function that takes in a polynomial and returns its degree? For example: suppose we have the ring `R = PolynomialRing(ZZ, 'x')`, and the polynomial `p = (x-1)*(x-2)`. The degree function I'm looking for should return 2 when applied to `p`. Does such a function exist??Tue, 30 Mar 2021 23:05:53 +0200https://ask.sagemath.org/question/56440/how-to-find-the-degree-of-a-polynomial/Answer by slelievre for <p>Is there a function that takes in a polynomial and returns its degree? For example: suppose we have the ring <code>R = PolynomialRing(ZZ, 'x')</code>, and the polynomial <code>p = (x-1)*(x-2)</code>. The degree function I'm looking for should return 2 when applied to <code>p</code>. Does such a function exist??</p>
https://ask.sagemath.org/question/56440/how-to-find-the-degree-of-a-polynomial/?answer=56444#post-id-56444Polynomials (and symbolic expressions) have a `degree` method.
Beware that even after defining `R` as in the question,
`x` is still a "symbolic variable" in the "symbolic ring".
In a fresh Sage session:
sage: R = PolynomialRing(ZZ, 'x') # defines R but not x
sage: x.parent()
Symbolic Ring
sage: q = (x - 1) * (x - 2)
sage: q
(x - 1)*(x - 2)
sage: q.parent()
Symbolic Ring
Symbolic expressions have a `degree` method that gives
the degree with respect to any chosen variable.
sage: q.degree(x)
2
Declare `x` as the indeterminate in `R`.
sage: x = R.gen()
Then:
sage: x.parent()
Univariate Polynomial Ring in x over Integer Ring
sage: p = (x - 1) * (x - 2)
sage: p
x^2 - 3*x + 2
sage: p.parent()
Univariate Polynomial Ring in x over Integer Ring
Or:
sage: p = R(q)
sage: p
x^2 - 3*x + 2
sage: p.parent()
Univariate Polynomial Ring in x over Integer Ring
To get the degree, use the `degree` method (no need
to specify that it is with respect to `x` now, since
`p` is a univariate polynomial):
sage: p.degree()
2
Sage slightly extends Python's syntax to enable defining
`R` and `x` at once. For example:
sage: R.<x> = PolynomialRing(ZZ)
is equivalent to:
sage: R = PolynomialRing(ZZ, 'x')
sage: x = R.gen()Wed, 31 Mar 2021 09:14:19 +0200https://ask.sagemath.org/question/56440/how-to-find-the-degree-of-a-polynomial/?answer=56444#post-id-56444