# How can I create a proper **dense** PolynomialRing over any ring?

I know that PolynomialRing has the keyword "sparse" which defaults to False.

sage: S = PolynomialRing(QQ, "x", sparse=False)
sage: S is PolynomialRing(QQ, "x")
True


But the output of .coefficients() is still sparse in the sense that it does only show non-zero coefficients

sage: p = S([1, 0, 2])
sage: p.coefficients()
[1, 2]


I know that I could reconstruct the polynomial using .exponents()

sage: p.exponents()
[0, 2]
sage: x = S.gen()
sage: p == sum(coef*x**exp for coef, exp in zip(p.coefficients(), p.exponents())
True


But is there an easy way to make .coefficients() return the true list of coefficients, i.e., [1, 0, 2]? Right now I would need it for a PolynomialRing over QQ but a solution for any ring would be ideal.

edit retag close merge delete

Side note: I think what I want was the default implementation at some time since code that I wrote on version=9.8 was based on the fact that it works like I want it. But now after updating to 10.5 the function raises IndexErrors (understandably).

( 2024-08-06 16:02:31 +0200 )edit

Sort by ยป oldest newest most voted

The internal representation is dense. You can (efficiently) get the dense list of coefficients as follows:

sage: p.coefficients(sparse=False)
[1, 0, 2]
sage: p.list()
[1, 0, 2]


Note that the implementation of the coefficients method (for the polynomial ring constructed with sparse=False) is the following:

def coefficients(self, sparse=True):
"""
Return the coefficients of the monomials appearing in self.
If sparse=True (the default), it returns only the non-zero coefficients.
Otherwise, it returns the same value as self.list().
(In this case, it may be slightly faster to invoke self.list() directly.)

EXAMPLES::

sage: _.<x> = PolynomialRing(ZZ)
sage: f = x^4 + 2*x^2 + 1
sage: f.coefficients()
[1, 2, 1]
sage: f.coefficients(sparse=False)
[1, 0, 2, 0, 1]
"""
zero = self._parent.base_ring().zero()
if sparse:
return [c for c in self.list() if c != zero]
else:
return self.list()

more