We found a possible bug in our Matlab
Afficher commentaires plus anciens
Sometimes we encounter a numerical problem e.g:
find([1.1:0.01:1.2]==1.14)
ans =
Empty matrix: 1-by-0
The cause is most likely numerical as if we add eps to 1.14, it suddenly works for 1.14: >> find([1.1:1e-2:1.2]==1.14+eps)
ans =
5
Please let us know if you have a fix
1 commentaire
"We found a possible bug in our Matlab"
Aaaah, the one millionth beginner has found this bug in MATLAB! It must be MATLAB's fault! Or perhaps instead today is good day to learn about floating point numbers (and how this is not an bug in MATLAB)?
Réponse acceptée
Plus de réponses (2)
Image Analyst
le 15 Jan 2017
1 vote
Not to beat a dead giraffe, but you can also find the same information about comparing floating point numbers in the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Walter Roberson
le 15 Jan 2017
This is not a bug. When you use == you are asking for exact comparison right down to the last bit. You are assuming that computations are carried out in decimal so that 0.1 and 0.01 are exactly represented, but calculations are carried out in binary which has no exact representation for 1/10 (exactly the same way that decimal has no exact finite representation for 1/7). The error in representation builds up when you use the : operator, which is not going to be adding exactly 1/100 each time, only a value very close to 1/100. And the starting value 1.1 also cannot be exactly represented in binary.
The result of this is that the : operation is going to produce a number that is close to 1.4 but not exactly equal to it and not exactly equal to how MATLAB converts 1.4 to binary. With == needing exact match, the comparison fails.
Try
format long g
(1.1:0.01:2) - 1.4
and you will see that one of the values is close to 0 but not exactly 0. If the value was exactly there then you would get a 0
You should avoid comparing floating point numbers for exact equality unless you have extracted the numbers from the same array. See ismembertol()
3 commentaires
itamar luzon
le 15 Jan 2017
John D'Errico
le 15 Jan 2017
itamar - No. You think you solved it. But you did not. See my comment above.
itamar luzon
le 15 Jan 2017
Catégories
En savoir plus sur Get Started with MATLAB dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!