Operator for approximate equality testing in Mathematica

I often need to check if there is expr1==expr2where the check for symbolic equality is tough, but a numerical check is enough

To deal with such cases, it would be convenient to TildeTildework like Equal, but instead of checking symbolic equality, he would replace the unknowns with numerical values ​​and check the numerical equality at several points.

Unknown are things that “look” like variables in an expression. I think they have a shape x, x[1,2]and Subscript[x,2,3]. Any advice is appreciated!

change

Usually I do something like below, but this requires variables to be specified, sometimes a change in the Chop tolerance is required, and the “10 samples” seem arbitrary. An ideal tester will be a function that works as Equalswell as guarantees reliable answers False. (in addition to Equalsthat has meaningful answers True)

approxEqual [expr1_, expr2_, vars_]: = 
  Chop [(expr1 - expr2 /. Thread [vars -> #]) & / @ 
     RandomReal [{- 1, 1}, {10, Length [vars]}]] == Table [0, {10}];
expr1 = 1 / Sqrt [2] Log [Cosh [q + x / Sqrt [2]] Sech [q - x / Sqrt [2]]];
expr2 = Sqrt [2] ArcTanh [Tanh [q] Tanh [x / Sqrt [2]]];
approxEqual [expr1, expr2, {q, x}]

As a side note, Maple seems to use this algorithm for such equality testing.

+3
2

, FindMaximum :

In[64]:= FindMaximum[expr1 - expr2, q, x]

During evaluation of In[64]:= FindMaximum::fmgz: Encountered a gradient that
is effectively zero. The result returned may not be a maximum; it may be a 
minimum or a saddle point. >>

Out[64]= {1.11022*10^-16, {q -> 1., x -> 1.}}

:

approxEqual[lhs_, rhs_, tol_: 10^-10] :=
 Module[{vars},
  vars = DeleteDuplicates[
    Cases[{lhs,rhs}, s_Symbol /; Not[ValueQ[s]], Infinity]
  ];
  Chop[
    First[
     Quiet[FindMaximum[Abs[lhs - rhs], Evaluate[Sequence @@ vars]]]
    ], 
    tol] == 0
  ]

In[65]:= approxEqual[expr1, expr2]
Out[65]= True

In[66]:= approxEqual[expr1, expr2, 10^-20]
Out[66]= False

, , AccuracyGoal/PrecisionGoal/WorkingPrecision/ .. FindMaximum. FindMaximum .

, TildeTilde, (.. ~~), StringExpression.

!

+5

, , . - , .
, numEqual=MakeEqualityTest[...] , , . lhs ~numEqual~rhs . , , , , , , github ( ).

:

  • Cases
  • Norm[#1-#2]& , ..
  • .
  • (, ).

:

numeq=MakeEqualityTester[];
(Cos[x]^2+Sin[x]^2)~numeq~1
Sqrt[x^2]~numeq~x

Out[5]= True
During evaluation of In[4]:= EqualityTest::notEqual: The expressions Sqrt[x^2] and x were not equal at the following point:
Out[6]= {x->-0.352399}

:

EqualityTest[1,Cos[x]^2+Sin[x]^2]
Out[7]= True

:

poseq=MakeEqualityTester[{
    Subscript[y,_]:>RandomReal[{10,11}],
    Automatic 
  },Tolerance-> 10^(-5)];
x ~poseq~ Sqrt[x^2]
Subscript[y,1] ~poseq~ Sqrt[Subscript[y,1]^2]

During evaluation of In[18]:= EqualityTest::notEqual: The expressions x and Sqrt[x^2] were not equal at the following point:
Out[19]= {x->-0.272029}
Out[20]= True
+1

Source: https://habr.com/ru/post/1775344/


All Articles