FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

Simplify[b - a] results in -a + b. I prefer b - a, which is a bit simpler (3 symbols instead of 4).

Can I make Mathematica to think the same way?

I believe one needs to redefine the ComplexityFunction.

{ asked by bcp }

ANSWER

It is not Simplify that changes b-a to -a+b. It happens automatically, and it cannot generally be prevented except by using Hold or HoldForm which will make it impossible to use the expression for calculations (until you remove the Hold wrapper again). But while you can't prevent changing b-a to -a+b internally, you can change how it will be displayed on screen, by using TraditionalForm.

Why does Mathematica not consider one form simpler than the other?

Let's look at the structure of these expressions:

In[1]:= Hold[b-a]//FullForm
Out[1]//FullForm= Hold[Plus[b,Times[-1,a]]]

In[2]:= Hold[-a+b]//FullForm
Out[2]//FullForm= Hold[Plus[Times[-1,a],b]]

The only difference is the ordering of the terms within Plus, but neither expression has fewer parts than the other. This is the consequence of the particular choice for their internal representation, which is shown above using FullForm.

Why does Mathematica reorder the terms of Plus?

Plus has the Orderless attribute. This attribute is used for functions that are commutative. The system will automatically bring any Orderless function to a canonical form by sorting its arguments the same way Sort would. See that documentation page for the sorting rules: symbols will generally be sorted alphabetically, so a comes before b.

It's not difficult to see why canonical forms are advantageous to use in computer algebra systems when it is at all possible to define and efficiently compute one. For example, it will make a comparison such as a+b==b+a trivial to carry out efficiently.

But I don't care what's simpler for a computer, $b-a$ is just more readable for humans!

You're right about that, that's why the function TraditionalForm will change the way expressions are displayed. It won't change their internal representation: it will still be Plus[Times[-1,a],b], i.e. something like (-1)*a + b. However it will change how they're displayed on screen and show $b-a$ for better readability.

I sometimes select the output cell and press Command-Shift-T to automatically convert the cell to TraditionalForm for better readability (e.g. it'll show matrices in 2D form and will order polynomials with higher order terms first).

{ answered by Szabolcs }
Tweet