Difference between == and === in Mathematica

后端 未结 5 1175
太阳男子
太阳男子 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: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
    

提交回复
热议问题