Difference between == and === in Mathematica

后端 未结 5 1146
太阳男子
太阳男子 2020-12-31 11:10

I was under the impression that = is an assignment, == is a numeric comparison, and === is a symbolic comparison (as well as in some o

相关标签:
5条回答
  • 2020-12-31 11:51

    I direct you to section 2.5: Equality checks of an excellent book by Leonid Shifrin.

    0 讨论(0)
  • 2020-12-31 11:52

    Equal refers to semantic equality whereas SameQ is syntactic equality. For instance, Sin[x]^2+Cos[x]^2 and 1 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, so SameQ gives False.

    Sin[x]^2 + Cos[x]^2 == 1
    Sin[x]^2 + Cos[x]^2 === 1
    Simplify[Sin[x]^2 + Cos[x]^2 == 1]
    

    Note that there's special handling of Real numbers, SameQ[a,b] can return True if a and b differ in the last binary digit. To do more restrictive identity testing, use Order[a,b]==0

    a = 1. + 2^-52;
    b = 1.;
    a === b
    Order[a, b]==0
    

    SameQ can return True for expressions that are syntactically different because expression heads may sort arguments automatically. You can prevent automatic sorting by using holding attributes. For instance

    c + d === d + c
    SetAttributes[SameQ, HoldAll]
    c + d === d + c
    
    0 讨论(0)
  • 2020-12-31 12:05

    == and === are very similar in the sense that it returns True if the lhs and rhs are equal. One example where they differ is when you compare numbers in different representation formats.

    In: 5.==5
    Out: True
    
    In: 5.===5
    Out: False
    

    Although they are the same numerically, (which is why == returns True), they aren't exactly identical.

    FYI, they are different functions internally. == is Equal, whereas === is SameQ.

    0 讨论(0)
  • 2020-12-31 12:10

    One important difference is that === always returns True or False. == can return unevaluated (which is why it's useful for representing equations.)

    In[7]:= y == x^2 + 1
    
    Out[7]= y == 1 + x^2
    
    In[8]:= y === x^2 + 1
    
    Out[8]= False
    

    There are some interesting cases where == returns unevaluated that are worth being aware of while programming. For example:

    In[10]:= {} == 1
    
    Out[10]= {} == 1 
    

    which can affect things like If[foo=={}, <true>, <false>].

    0 讨论(0)
  • 2020-12-31 12:11

    lhs===rhs yields True if the expression lhs is identical to rhs, and yields False otherwise.

    and

    lhs==rhs returns True if lhs and rhs are identical.

    Reference from here and here.

    0 讨论(0)
提交回复
热议问题