WolframLang: Equality Test
There are two functions for testing equality.
SameQ
is good for testing symbolic expressions. It returnTrue
if both are exactly the same. It always returnTrue
orFalse
.Equal
is good for testing numerical expressions. It may return expression as is.
SameQ[expr1, expr2]
-
🔸 SHORT SYNTAX:
===
return
True
if two expressions are symbolically identical, elseFalse
.examples:
{a,b,c} === {a,b,c}
returnTrue
because they are the same expression term-by-term.3 === 3.0
returnFalse
because one is exact number while the other is approx.3 === xyz
returnFalse
because xyz is a symbol. (unless it has a value of 3)
x = 3; y = 3.0; x === y (* False *)
Equal[expr1, expr2]
-
🔸 SHORT SYNTAX:
==
- return
True
if two expressions are semantically equal. (e.g.3
vs3.0
) - return
False
if two expressions are not semantically equal. - return whole expression as is, if semantic equality cannot be determined easily or WolframLang quirk.
3 == 3 (* True *) 3 == 3.0 (* True *) {3} == {3.0} (* True *)
🛑 WARNING:
Equal
does not returnTrue
orFalse
even for obvious cases.{} == 2 (* return expression as is. Version 13 *) (* using Reduce makes it true *) Reduce[ {} == 2 ] === True
(* WARNING *) {{1}} == {2} (* return expression as is. Version 13 *) {{1.0}} == {2.0} (* return expression as is *)
- return
Inequality
UnsameQ
-
🔸 SHORT SYNTAX:
=!=
Same as
Not[SameQ[x, y]]
. Unequal
-
🔸 SHORT SYNTAX:
!=
Same as
Not[Equal[x, y]]
.
💡 TIP: What Function to Use for Equality Test
- Use
SameQ
when the expressions do not contain numbers with decimal point. It always returnTrue
orFalse
. - Use
Equal
when you have numbers with decimal point.