4
$\begingroup$

Very elementary:

2 + 3 == 5 evaluates to True and 5 == 5 evaluates to True.

How do I check if two numerical expressions are identical?

In other words, I want a matching test that says 2 + 3 does not match 5, but 5 does match 5.
More generally, how do you test whether algebraic expressions are identical?

$\endgroup$
0

2 Answers 2

6
$\begingroup$

Here's a try for the first question:

reallySameQ[a_, b_] := SameQ[Hold[a], Hold[b]]
SetAttributes[reallySameQ, HoldAllComplete]
reallySameQ[5, 5]
(* True *)
reallySameQ[2 + 3, 5]
(* False *)
$\endgroup$
4
$\begingroup$

Following WReach's fine explanation here one cannot even rely on SameQ to check for identical expressions; instead it seems one needs Order, therefore with holding added:

SetAttributes[identicalQ, HoldAll]

identicalQ[x_, y_] := Order[Unevaluated @ x, Unevaluated @ y] == 0

Now:

identicalQ[2 + 3, 5]

identicalQ[5, 5]
False

True
$\endgroup$
5
  • $\begingroup$ I was waiting for your response :D, +1 ^^ $\endgroup$
    – Sektor
    Commented May 19, 2015 at 19:52
  • 1
    $\begingroup$ @Mr.Wizard can into much upvotes! Though admittedly, WReach`s answer dissapoints me. You read things like that, then you want to go hide under a rock and kill yourself, because nothing makes sense anymore. $\endgroup$
    – LLlAMnYP
    Commented May 19, 2015 at 21:09
  • $\begingroup$ @LLlAMnYP I admit that his answer reveals a less clean world that one would like, and it may come as a shock, but at the same time it makes the case for why such things are difficult to handle. Most of the time it seems to work out OK, and with Mathematica's exact/symbolic and arbitrary precision capabilities there are more solutions available to us than (easily) to most programmers. $\endgroup$
    – Mr.Wizard
    Commented May 20, 2015 at 1:56
  • 1
    $\begingroup$ Tally spawning 3 examples of 2.2...006 and putting them in different groups was what really made my day though. $\endgroup$
    – LLlAMnYP
    Commented May 20, 2015 at 7:21
  • $\begingroup$ @LLlAMnYP I had forgotten about that part. $\endgroup$
    – Mr.Wizard
    Commented May 20, 2015 at 7:24

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.