Ask Your Question

Is there a way to prevent Sage from rearranging expressions?

asked 2019-09-27 09:20:52 -0500

I feel this question may be similar to but haven't been able to resolve on my own.

If I enter an expression like x = a - b, then print out x to check what I've entered, Sage will output this as [x = ] -b + a. Is there a way for Sage to confirm the input as I typed it, then rearrange it in another step? With more complicated expressions, it takes a lot longer to verify that I haven't made an entry mistake.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2019-09-27 13:41:25 -0500

Emmanuel Charpentier gravatar image

updated 2019-09-27 13:45:47 -0500

This is a Frequently Asked Question...

Short answer: Sage may transform the expressions for you (e.g.: factor, expand, simplify, as well as specialized transforms such as trig_reduce or canonicalize_radical), but you don't have control of the exact form. This is determined by Sage's (often Maxima's) heuristics. Since there is no algorithmic definition of the "right" form, your taste may clash with Sage's developer's...

sage: E=b-a
sage: E
-a + b

is indeed annoying. But you may see better by asking:

sage: -E
a - b

Similarly, you can take advantage of Sage's abilities to transform expressions to do, for example, "intelligent checks". For example, you can isolate various parts of an expression by using coeffocients, to get subexpressions easier to check. Imagine you want to check some trig expression: such as:

sage: sin(13*x).trig_expand()
13*cos(x)^12*sin(x) - 286*cos(x)^10*sin(x)^3 + 1287*cos(x)^8*sin(x)^5 - 1716*cos(x)^6*sin(x)^7 + 715*cos(x)^4*sin(x)^9 - 78*cos(x)^2*sin(x)^11 + sin(x)^13

To check this, it might be easier to ask for:

sage: sin(13*x).trig_expand().coefficients(sin(x))
[[13*cos(x)^12, 1],
 [-286*cos(x)^10, 3],
 [1287*cos(x)^8, 5],
 [-1716*cos(x)^6, 7],
 [715*cos(x)^4, 9],
 [-78*cos(x)^2, 11],
 [1, 13]]

which is, arguably, easier to understand and check... You can also reverse your transformations in order to check that you get your original expression back:

sage: sin(13*x).trig_expand().trig_reduce()

A frequent application is deriving a difficult-to-obtain antiderivative (should be mandatory, IMHO...). Similarly, numerical integration can be used to check a suspicious definite integration ; in the same vein, graphics can be helpful...

Another direction is to try and find common subexpressions and replacing them by short symbolic names. Look for cse in sympy, which can be of help...

edit flag offensive delete link more

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: 2019-09-27 09:20:52 -0500

Seen: 51 times

Last updated: Sep 27 '19