Weird result, why I can't find -0.809 and 0.309 in -1:0.001:1???
1 view (last 30 days)
Show older comments
Jingli Xie
on 4 Mar 2020
Commented: Steven Lord
on 4 Mar 2020
why I can't find -0.809 and 0.309 in -1:0.001:1???
1 Comment
Stephen23
on 4 Mar 2020
Edited: Stephen23
on 4 Mar 2020
"why I can't find -0.809 and 0.309 in -1:0.001:1???"
Because they are not there.
In fact, those exact values don't even exist as binary floating point numbers.
"Weird result"
This is a completely expected result with binary floating point numbers:
This is worth reading as well:
Accepted Answer
David Goodmanson
on 4 Mar 2020
Edited: David Goodmanson
on 4 Mar 2020
Hello JX,
you are looking for exact equality with floating point numbers, and a exact equality does not always occur.
x = -1:.001:1;
format long
x(1810)
ans = 0.809000000000000 % looks good
x(1810) - .809
ans = -1.110223024625157e-16 % isn't good
Since there are only a finite number of bits (64 for double precision numbers like these), most floating point numbers cannot be stored exactly in memory. Here there is disagreement in the 16th decimal place, which is to be expected in some (not all) of the 2001 cases for the x array.
If you take a look with format hex, the way these numbers are actually stored,
>> format hex
x(1810)
ans = 3fe9e353f7ced916
809
ans = 3fe9e353f7ced917
you can see that first, .809 is stored as well as possible with 64 bits but not exactly (as would be the case with a bunch of trailing hex zeros), and second that the two numbers differ by 1 in the last bit. The equality check fails.
3 Comments
Stephen23
on 4 Mar 2020
"How can I find -0.809 and 0.309 in -1:0.001:1?"
Never compare binary floating point values for exact equality.
Always compare the absolute difference against a tolerance, e.g.:
tol = 1e-5;
idx = abs(A-B)<tol
Steven Lord
on 4 Mar 2020
Another way to compare with a tolerance is to use ismembertol.
>> ismembertol(-0.809, -1:0.001:1, eps)
ans =
logical
1
If I'd used a tolerance of 0 as the third input, to only detect cases where -0.809 is an exact down-to-the-last-bit match for an element in the vector, the answer would have been false (logical 0.)
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!