Is there a “normal” EqualQ function in Mathematica?

后端 未结 7 574
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 03:49

On the documentation page for Equal we read that

Approximate numbers with machine precision or higher are considered equal if they d

7条回答
  •  囚心锁ツ
    2020-12-24 04:38

    I think that you really have to specify what you want... there's no way to compare approximate real numbers that will satisfy everyone in every situation.

    Anyway, here's a couple more options:

    In[1]:= realEqual[lhs_,rhs_,tol_:$MachineEpsilon] := 0==Chop[lhs-rhs,tol]
    
    In[2]:= Equal[1.0000000000000021,1.0000000000000021]
            realEqual[1.0000000000000021,1.0000000000000021]
    Out[2]= True
    Out[3]= True
    
    In[4]:= Equal[1.0000000000000022,1.0000000000000021]
            realEqual[1.0000000000000022,1.0000000000000021]
    Out[4]= True
    Out[5]= False
    

    As the precision of both numbers gets higher, then they can always be distinguished if you set tol high enough.

    Note that the subtraction is done at the precision of the lowest of the two numbers. You could make it happen at the precision of the higher number (which seems a bit pointless) by doing something like

    maxEqual[lhs_, rhs_] := With[{prec = Max[Precision /@ {lhs, rhs}]}, 
      0 === Chop[SetPrecision[lhs, prec] - SetPrecision[rhs, prec], 10^-prec]]
    

    maybe using the minimum precision makes more sense

    minEqual[lhs_, rhs_] := With[{prec = Min[Precision /@ {lhs, rhs}]}, 
      0 === Chop[SetPrecision[lhs, prec] - SetPrecision[rhs, prec], 10^-prec]]
    

提交回复
热议问题