# collect is not ordering terms

I was a bit surprised by the following behaviour:

sage: var('c0 c1 c2 x0 x1 x')
(c0, c1, c2, x0, x1, x)
sage: (c0+(x-x0)*(c1+(x-x1)*c2)).collect(x)
c2*x^2 - c2*x*x0 - c2*x*x1 + (c2*x1 - c1)*x0 + c1*x + c0


I assumed that collect would order my terms into coefficients for powers of x. At the very least, I'd have expected

 c2*x^2 - c2*x*x0 - c2*x*x1 + c1*x + (c2*x1 - c1)*x0 + c0
|   x^2 |    x         x         x |            1        |


Although my real goal would have been

c2*x^2 - (c2*x0 - c2*x1 + c1)*x + (c2*x1*x0 - c1*x0 + c0)


I see from the documentation that there is no description at all what collect does, except returning a symbolic expression. Am I missing the point of that method?

I know I can get at the coefficients as a list using the coeffs method, but I'd prefer the form as a sum. It seems that even turning that back into a sum, my terms get reordered:

sage: sum([a*x^p for a, p in (c0+(x-x0)*(c1+(x-x1)*c2)).coeffs(x)])
c2*x^2 + (c2*x1 - c1)*x0 - (c2*x0 + c2*x1 - c1)*x + c0


This indicates that the problem might not be in collect itself, but rather in the way symbolic expressions are stored and printed.

My best solution currently is a manually computed string:

sage: print(' + '.join(['({})*{}'.format(a.expand(), x^p) for a, p in
(c0+(x-x0)*(c1+(x-x1)*c2)).coeffs(x)]))
(c2*x0*x1 - c1*x0 + c0)*1 + (-c2*x0 - c2*x1 + c1)*x + (c2)*x^2


Is there a better way to achieve this result?

edit retag close merge delete

Sort by » oldest newest most voted

It does seem that a sort command or option is missing. I can get closer to what you want with:

var('c0 c1 c2 x0 x1 x')
p=(c0+(x-x0)*(c1+(x-x1)*c2))
p.expand().collect(x)


This collects terms better, but they are not in order by degree.

more

Incidentally, I think Maple used to have this problem as well. It had to do with how the terms were stored in memory, and if you wanted a different sorting, you had to ask for it. I haven't used Maple much in a long time so that might not be true of recent versions.

( 2012-11-19 05:49:39 -0500 )edit