I was under the impression that =
is an assignment, ==
is a numeric comparison, and ===
is a symbolic comparison (as well as in some other languages ==
being equal to
and ===
being identical to
. However, looking at the following it would appear that this is not necessarily the case...
In: x == x
Out: True
In: x === x
Out: True
In: 5 == 5
Out: True
In: 5 === 5
Out: True
In: x = 5
Out: 5
In: 5 == x
Out: True
In: 5 === x
Out: True
In: 5 5 == 5x
Out: True
In: 5 5 === 5x
Out: True
In: x == y
Out: x == y
In: x === y
Out: False
In: y = x
Out: 5
In: x == y
Out: True
In: x === y
Out: True
So what exactly is the difference between == and === in Mathematica? I have been looking at the documentation but I still don't quite understand it.
One important difference is that
===
always returnsTrue
orFalse
.==
can return unevaluated (which is why it's useful for representing equations.)There are some interesting cases where
==
returns unevaluated that are worth being aware of while programming. For example:which can affect things like
If[foo=={}, <true>, <false>]
.and
Reference from here and here.
I direct you to section 2.5: Equality checks of an excellent book by Leonid Shifrin.
==
and===
are very similar in the sense that it returnsTrue
if the lhs and rhs are equal. One example where they differ is when you compare numbers in different representation formats.Although they are the same numerically, (which is why
==
returnsTrue
), they aren't exactly identical.FYI, they are different functions internally.
==
isEqual
, whereas===
isSameQ
.Equal
refers to semantic equality whereasSameQ
is syntactic equality. For instance,Sin[x]^2+Cos[x]^2
and1
are the same number, so they are equal semantically. Since this can not be determined without more transformations,Equal
returns unevaluated. However, actual expressions are different, soSameQ
givesFalse
.Note that there's special handling of
Real
numbers,SameQ[a,b]
can returnTrue
ifa
andb
differ in the last binary digit. To do more restrictive identity testing, useOrder[a,b]==0
SameQ
can returnTrue
for expressions that are syntactically different because expression heads may sort arguments automatically. You can prevent automatic sorting by using holding attributes. For instance