Is there a way to use Head to detect a symbolic fraction? In particular I find,




where I would like to get Head[a/b] = Rational. I want to test if a symbolic expression is a fraction so I can use it in another function.

  • 2
    $\begingroup$ Rational is for numbers. Since a and b can be anything, since they are just symbols, I do not think it makes sense to say a/b is rational. If all you want is to check for the form, may be you can look at FullForm[a/b] and check for this form in your function by pattern matching? $\endgroup$ – Nasser Feb 2 '15 at 10:20
  • $\begingroup$ Related: (18987) $\endgroup$ – Mr.Wizard Feb 2 '15 at 12:55

It seems to me that Denominator helps a lot:

fractionQ = Denominator@# =!= 1 &;

fractionQ /@ {a/b, 1/a, 1/5, b/2, a, .5}
(* {True, True, True, True, False, False} *)

The goal is not so clear for me, but probably something like this can be useful:

test = MatchQ[#, HoldPattern[_. _^-1] | _Rational | HoldPattern[_ Rational[1, _]] ] &

test /@ {a/b, 1/a, 1/5, a, .5, b/2}
{True, True, True, False, False, True}

Notice the dot in _., it is crucial for detecting 1/a since there is no Times really.


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.