4
$\begingroup$

When I Trace a rational number, I get this quite complicated output:

1/2 // Trace

{{1/2,1/2},1/2,1/2}

which under the hood looks like

{{HoldForm[1/2], HoldForm[1/2]}, HoldForm[1/2], HoldForm[1/2]}

At the same time, 1/2 is represented as Rational:

1/2 // FullForm

Rational[1, 2]

But if we do:

Rational[1, 2] // Trace

we get very simple output, which would be expected:

{Rational[1,2],1/2}

with underlying output being

{HoldForm[Rational[1, 2]], HoldForm[1/2]}

So, the question is: why MMA does so many steps when evaluating a rational number entered in a "pure" form and doesn't do it when Rational is used explicitly?

$\endgroup$
1
  • 1
    $\begingroup$ Have you looked at Trace[1/2] // FullForm already? $\endgroup$ Commented Jan 23, 2017 at 16:44

1 Answer 1

5
$\begingroup$

Using FullForm should help illuminate things:

Hold[1/2]//FullForm

Hold[Times[1,Power[2,-1]]]

We see that 1/2 is a bit more complicated than you might have expected. To evaluate this, you need to first evaluate Power[2, -1], and then you need to multiply that output with 1. So, let's see what happens in the Trace:

1/2//Trace
% /. h_HoldForm -> FullForm[h]

{{1/2,1/2},1/2,1/2}

{{HoldForm[Power[2,-1]],HoldForm[Rational[1,2]]},HoldForm[Times[1,Rational[1,2]]],HoldForm[Rational[1,2]]}

The Trace shows that the evaluation proceeded exactly as expected based on the FullForm of the input.

$\endgroup$
3
  • $\begingroup$ Thank you! That makes sense. What doesn't though, is why 1/2 needs to be presented in such a weird way. Any ideas why? $\endgroup$
    – Stitch
    Commented Jan 23, 2017 at 17:54
  • $\begingroup$ Probably should make that a different question, a complete answer doesn't really work in a comment. The basic answer is to look at the cell expression corresponding to the input 1/2 (or more generally x/y) using Cell | ShowExpression, and think about how one would convert that cell to an expression. $\endgroup$
    – Carl Woll
    Commented Jan 23, 2017 at 18:13
  • $\begingroup$ Thank you again. Will look into it and possibly post a question. $\endgroup$
    – Stitch
    Commented Jan 23, 2017 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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