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

1 vue (au cours des 30 derniers jours)
Jingli Xie
Jingli Xie le 4 Mar 2020
Commenté : Steven Lord le 4 Mar 2020
why I can't find -0.809 and 0.309 in -1:0.001:1???
  1 commentaire

Connectez-vous pour commenter.

Réponse acceptée

David Goodmanson
David Goodmanson le 4 Mar 2020
Modifié(e) : David Goodmanson le 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 commentaires
Stephen23
Stephen23 le 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
Steven Lord le 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.)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by