6
$\begingroup$

Is there a fast function "ExactExpressionQ" to test whether an expression is exact vs inexact? I'm looking for something like ExactNumberQ that works for expressions.

My attempt at this is

ExactExpressionQ[expr_] := FreeQ[expr, _Real|_Complex?InexactNumberQ]

ExactExpressionQ[0]
ExactExpressionQ[0.]
ExactExpressionQ[(2.1 + I) x]
ExactExpressionQ[Sin[x]]

(* True *)
(* False *)
(* False *)
(* True *)

Is there something better?

$\endgroup$
8
  • 1
    $\begingroup$ Is it OK that e.g. Floor[1.4*x] is treated as inexact? I think Floor always produces exact integers if given numbers, whether exact or inexact. $\endgroup$ Jun 4, 2016 at 13:42
  • $\begingroup$ That's a good point; one would have to think about certain functions returning exact results even if their input may be inexact. For the case at hand, let's just ask that ExactExpressionQ tests whether the input expression is literally exact or not. $\endgroup$
    – QuantumDot
    Jun 4, 2016 at 14:07
  • $\begingroup$ One issue is that Complex can head an exact number. Have to peek inside... $\endgroup$
    – John Doty
    Jun 4, 2016 at 14:28
  • 1
    $\begingroup$ You can shorten your definition to ExactExpressionQ[expr_] := FreeQ[expr, _?InexactNumberQ] $\endgroup$
    – Bob Hanlon
    Jun 4, 2016 at 14:29
  • 1
    $\begingroup$ It seems giving levelspec -1 would help and still give the desired result. (Can't test here though). $\endgroup$
    – george2079
    Jun 4, 2016 at 15:06

1 Answer 1

1
$\begingroup$

Using george2079's suggestion, the code can be tweaked to

ExactExpressionQ[expr_] := FreeQ[expr, _Real|_Complex?InexactNumberQ, {-1}]

for better performance.

$\endgroup$

Your Answer

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

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