9
$\begingroup$

Whenever I write a rational number times a variable, i.e.:

(2/3)a

the result Mathematica displays looks very cringeworthy:

$$\frac{2a}{3}$$

I would prefer the output to look like

$$\frac{2}{3}a$$

Even a substitution rule like

/.(x_Integer q_)/y_Integer -> (x/y) q

does not correct the issue. Is it possible to make the output look proper?

$\endgroup$
  • 1
    $\begingroup$ You have a strange idea of what's proper. I'd take the first form any time... $\endgroup$ – V.E. Oct 29 '15 at 5:50
  • 2
    $\begingroup$ @V.E. for me it depends; with long-ish polynomials, I do like having the fractional coefficient and the monomial being separated by a thin space. $\endgroup$ – J. M. will be back soon Oct 29 '15 at 6:25
7
$\begingroup$

I believe this is what $PrePrint is for, since you only want to affect how the expression looks, and I'm guessing you want it to happen automatically for every input. Using $PrePrint thus allows you to use Out[n] without worrying about the held expressions.

This seems to work (but I would like to find a better way to take care of the signs between terms in a sum):

$PrePrint = # /. r_Rational x_Symbol :> Sign[r] HoldForm[Evaluate[Abs[r]]] HoldForm[x] &

You can add more replacement rules if you like of course, to treat e.g. polynomials:

$PrePrint = # /. {r_Rational x_Symbol :>
                   Sign[r] HoldForm[Evaluate[Abs[r]]] HoldForm[x],
                  r_Rational x_Symbol^i_Integer :>
                   Sign[r] HoldForm[Evaluate[Abs[r]]] HoldForm[x^i]
                 } &
$\endgroup$
4
$\begingroup$

I would do this by using a custom MakeBoxes rule:

MakeBoxes[Times[a__, r_Rational], StandardForm] := MakeBoxes[Times[Defer[r], a]]

Some examples:

Graphics[Circle[]]/2+Graphics[Rectangle[]]/3
Series[Sin[x], {x, 0, 10}]
Expand[(x-y)^4/24]

enter image description here

One nice thing about this approach is that the output is copy/pastable.

The other answer doesn't work right for any of these inputs, and the outputs generated are not copy/pastable.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.