Ask Your Question
0

Is there a way to prevent Sage from rearranging expressions?

asked 2019-09-27 16:20:52 +0100

nikhilvs gravatar image

I feel this question may be similar to ask.sagemath.org/question/46502/rearranging-expressions-to-minimize-negative-signs/ 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
1

answered 2019-09-27 20:41:25 +0100

Emmanuel Charpentier gravatar image

updated 2019-09-27 20:45:47 +0100

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()
sin(13*x)

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

Stats

Asked: 2019-09-27 16:20:52 +0100

Seen: 302 times

Last updated: Sep 27 '19