Ask Your Question

collect is not ordering terms

asked 2012-11-17 18:02:50 +0100

MvG gravatar image

updated 2012-11-18 03:50:55 +0100

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
(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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2012-11-19 08:43:16 +0100

calc314 gravatar image

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')

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

edit flag offensive delete link 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.

calc314 gravatar imagecalc314 ( 2012-11-19 12:49:39 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2012-11-17 18:02:50 +0100

Seen: 654 times

Last updated: Nov 19 '12