I will say some words here, not in a comment, since the space is more generous.
First of all, methods implemented for some objects are often implemented with a special purpose. They may be used in further implemented algorithms, or are implemented to provide a "library usage". The questions assumes tacitly, that the two methods coefficients
and monomials
of the object f
, that i chose in a different way
sage: P.<x> = PolynomialRing(QQ)
sage: f = 11*x^3 - 17*x^7 + 56*x^10 + 9*x^5
sage: f.parent()
Univariate Polynomial Ring in x over Rational Field
sage: type(f)
<class 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint'>
should be related to each other. No, in this case the programmer expects one method. Let us ask for the coefficients and the monomials involved:
sage: f.coefficients()
[11, 9, -17, 56]
sage: f.monomials()
[x^10, x^7, x^5, x^3]
In the doc string of the last method we have the information:
sage: f.monomials??
::::::::::::: many lines then... :::::::::::::
Source:
def monomials(self):
"""
Return the list of the monomials in ``self`` in a decreasing order of their degrees.
EXAMPLES::
sage: P.<x> = QQ[]
sage: f = x^2 + (2/3)*x + 1
so it is an intention to sort in this manner.
For the coefficients, the natural, "expected" behavior is kept, we can for instance ask for:
sage: f.coefficients()
[11, 9, -17, 56]
sage: f.coefficients(sparse=True)
[11, 9, -17, 56]
sage: f.coefficients(sparse=False)
[0, 0, 0, 11, 0, 9, 0, -17, 0, 0, 56]
sage: f.list()
[0, 0, 0, 11, 0, 9, 0, -17, 0, 0, 56]
sage: f.dict()
{3: 11, 5: 9, 7: -17, 10: 56}
to extract in a way or an other the information on the polynomial.
That inconsistent behavior in the univariate case looks undesirable to me, but changing it would break compatibility with existing code (if anyone ever used it). As a workaround you can use
P.<x> = PolynomialRing(QQ, 1)
to create a multivariate polynomial ring with one variable.If the inconsistency is not changed, then it should at least be mentioned in the documentation. It took me quite a while to figure out why my code did not produced the desired result.
It also may be unexpected that if
f = 1 + 2*x**2
, thenf.coefficients()
will return(1, 2)
: by default it only includes nonzero coefficients. Note thatf.exponents()
returns information consistent withf.coefficients()
. Maybe they're supposed to be used together?I created https://trac.sagemath.org/ticket/33813 to improve the documentation for these methods.