On the documentation page for Equal
we read that
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).
Here are examples (32 bit system; for 64 bit system add some more zeros in the middle):
In[1]:= 1.0000000000000021 == 1.0000000000000022
1.0000000000000021 === 1.0000000000000022
Out[1]= True
Out[2]= True
I'm wondering is there a "normal" analog of the Equal
function in Mathematica that does not drop last 7 binary digits?
This tests if two object are identical, since 1.0000000000000021 and 1.000000000000002100 differs in precision they won't be considered as identical.
Try this:
The choice of base 2 is crucial to ensure that you are comparing the internal representations.
I propose a strategy that uses
RealDigits
to compare the actual digits of the numbers. The only tricky bit is stripping out trailing zeroes.One other way to define such function is by using SetPrecision:
This seems to work in the all cases but I'm still wondering is there a built-in function. It is ugly to use high-level functions for such a primitive task...
I'm not aware of an already defined operator. But you may define for example:
Such as:
Edit
If you want to generalize for an arbitrary number of digits, you can do for example:
So that your counterexample in your comment also works.
HTH!
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:
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
maybe using the minimum precision makes more sense