# How to reorder terms in an expression to follow a specific order?

Suppose I have the following code:

ti = var('ti', latex_name = 't_i')
yi = var('yi', latex_name = 'y_i')
expr1 = yi -ti

expr1 will display as $$-{t_i} + {y_i}$$

Is there a way I can rewrite expr1 so that it will display as:

$${y_i} -{t_i}$$

?

I've tried using hold=True like so:

expr1 = yi.add(-ti, hold = True)

but that did not work.

edit retag close merge delete

Sort by » oldest newest most voted

This following answer can be considered only in case when algebraic expressions are involved / needed. So in the implicit need there should not come some exp( yi-ti ) + ... into play. (A comment has not so much space, so it is an answer.)

There is a good control for the order of variables when using polynomial rings. Let us consider the following sample code:

sage: R.<yi,ti> = PolynomialRing( QQ, order='degrevlex' ) # default order
sage: yi - ti
yi - ti
sage: R.latex_variable_names()    # we want other than...
['\\mathit{yi}', '\\mathit{ti}']

The constructor PolynomialRing could have been called without the specific order, which is the default one. Note that if instead of variable indices i or j or ... we use digits and numbers $0,1,2,\dots,10,11,12,\dots$ , the names are set automatically with an underscore, e.g.

sage: PolynomialRing(QQ, 'x', 4)
Multivariate Polynomial Ring in x0, x1, x2, x3 over Rational Field
sage: PolynomialRing(QQ, 'x', 4).latex_variable_names()
['x_{0}', 'x_{1}', 'x_{2}', 'x_{3}']

Starting from the initial sample code, a way to convince the machine to do "the right thing" would be:

sage: R.<y_i,t_i> = PolynomialRing( QQ, order='degrevlex' ) # default order
sage: yi, ti = y_i, t_i

For instance in this setting:

sage: yi - ti
y_i - t_i
sage: factor( yi^3 - ti^3 )
(y_i - t_i) * (y_i^2 + y_i*t_i + t_i^2)

I am using the sage interpreter, here the prints will always have underscores... For me this would not be ok...

An other way to proceed would be to let the variable names as they are and set explicheatly the latex names. See also this link where a somehow related question was answered. (Same comments apply here.)

Sample code in our situation:

sage: R.<yi,ti> = PolynomialRing( QQ ) # default order
sage: yi-ti
yi - ti
sage: print R._latex_names
['\\mathit{yi}', '\\mathit{ti}']
sage: R._latex_names = [ 'y_i', 't_i' ]
sage: yi-ti
yi - ti
sage: latex( _ )
y_i -  t_i
sage: latex( factor( y_i^4-t_i^4 ) )
(y_{i} -  t_{i}) \cdot (y_{i} + t_{i}) \cdot (y_{i}^{2} + t_{i}^{2})

(The "cheat" was to use the underscore-method _latex_names, which may be changed internally from version to version without warning, but i could not find any setter.) This last way to go may be relevant, but only in case there is a latex parser in between. The brackets came in between indices after the underscores!

more