Bug in equality checks? 28.15e-3 == 28.15/1000 false

Why does this happen? It does not regocnize equality on 7.48e-3 == 7.48/1000, but it does on 7.47e-3 == 7.47/1000 as well. Another example below.
28.1e-3 == 28.1/1000
ans = logical
1
28.15e-3 == 28.15/1000
ans = logical
0

 Accepted Answer

Wellcome to the world of floating-point approximation error!
This is roughly equivalent to expressing in decimals. The result is 0.3 an infinite number of 3 following it, never being excactly equal to .
.

9 Comments

Thanks for the information. I thought it would consider the floating point error the same way on both sides of the equation so I thought it was a bug as for some cases worked and some did not.
If I am looking for values with decimals on tables, how do I bypass this error? Is there a smart way or I need to check if the value is within value+- 10*eps for example?
My pleasure!
The usual approach is to include a tolerance, something like this (using the requested criterion of 10*eps) —
TF1 = (28.15e-3 - 28.15/1000) == 0
TF1 = logical
0
TF2 = (28.15e-3 - 28.15/1000) <= 10*eps
TF2 = logical
1
So instead of testing for equality, do essentially the same thing with a subtraction, test it against the criterion, and return a logical value result.
.
As always, my pleasure!
.
Shouldn't that be:
TF2 = abs(28.15e-3 - 28.15/1000) <= 10*eps
" I thought it would consider the floating point error the same way on both sides of the equation"
Nope. In general, different operations will accumulate different floating point error.
Writing a number is quite a different operation to dividing two other numbers.
Then I'm very confused. If the idea is to test for "equality" then not including the abs check will lead to results like this:
TF2 = (-10 - 28.15/1000) <= 10*eps
TF2 = logical
1
I think the abs() is needed because one quantized expression could be above or below the other quantized expression, and I don't think you'd know which it will be in general.
Exactly and well said. I should have included a statement to that effect in my comment

Sign in to comment.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Products

Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!