5
$\begingroup$

Suppose I have two floats (e.g. {x,y} = RandomReal[{0,1},2]). Might there be a situation where all three comparisons evaluate to False (i.e. x > y, x < y and x == y)? I am thinking that the values might not be that stable and the equality might fail. Should something like Around be used instead? I am not fully understanding what is going on behind the hood with == operator and how stable the floats are and how stably they can be carried over.

$\endgroup$
3
  • 1
    $\begingroup$ see mathematica.stackexchange.com/questions/76896/… in the old days, i.e. when using Fortran, one checks if 2 numbers are the same or not by checking if the absolute difference between them is less than some epsilon (i.e. the machine epsilon) or not. $\endgroup$ – Nasser Apr 5 '20 at 3:13
  • $\begingroup$ @Nasser, thanks! Is there a way to compare two floats with a margin d? By IntervalIntersection? Or there is a better, more standard way? $\endgroup$ – Al Guy Apr 5 '20 at 3:21
  • 2
    $\begingroup$ From the doc for Equal, "Approximate numbers with machine precision or higher are considered equal if they differ in at most their last seven binary digits (roughly their last two decimal digits)." and "For numbers below machine precision, the required tolerance is reduced in proportion to the precision of the numbers." $\endgroup$ – Bob Hanlon Apr 5 '20 at 3:32
5
$\begingroup$

Both Equal and SameQ compare with tolerance. You can find the tolerances as

Internal`$EqualTolerance
(* 2.10721 *)

Internal`$SameQTolerance
(* 0.30103 *)

These values are to be interpreted as decimal digits. The numbers are considered equal if they differ in at most this many digits. Since the numbers are stored in binary, it makes more sense to look at the tolerances in binary digits:

Internal`$EqualTolerance Log2[10]
(* 7. *)

Internal`$SameQTolerance Log2[10]
(* 1. *)

Might there be a situation where all three comparisons evaluate to False (i.e. x > y, x < y and x == y)?

I do not think so.

Table[
 With[{x = 1 + n $MachineEpsilon}, {1 < x, 1 == x, 1 > x}],
 {n, -100, 100}
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.