MATLAB: Weird result, why I can’t find -0.809 and 0.309 in -1:0.001:1??

findfloating pointweird

why I can't find -0.809 and 0.309 in -1:0.001:1???

Best Answer

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.