bug in find function
Mostrar comentarios más antiguos
here is my exemple:
a = [-1:0.01:1];
n1 = find(a == -0.93); n2 = find(a == -1+0.07);
output:
n1 = [] (empty)
n2 = 8
can someone help?
Respuestas (2)
"bug in find function"
There is no bug in find. You have just discovered that two different floating point numbers are different. This is why you should not test floating point values for equality, and instead test the absolute difference against a tolerance:
abs(A-B)<tol
You are using a computer which stores values as binary floating point numbers. In exactly the same way that you cannot write 1/3 exactly using a finite decimal fraction, it is impossible to store -0.93 exactly using a finite binary floating point number. So although you might think that you have -0.93, in fact the real values stored in computer memory is slightly different from this.
The simplest solution for your code is to compare an absolute difference and a tolerance.
What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that that number does not really have the exact value -0.93. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see -0.93 displayed tells you nothing about the "real" floating point number's value.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
3 comentarios
Benzy Laufer
el 16 de Oct. de 2018
Bruno Luong
el 16 de Oct. de 2018
Try this:
a = [-1:0.01:1];
n1 = find(ismembertol(a,-0.93))
n2 = find(ismembertol(a,-1+0.07))
n1 =
8
n2 =
8
>>
Benzy Laufer
el 16 de Oct. de 2018
Image Analyst
el 16 de Oct. de 2018
0 votos
A thorough discussion/explanation is in the FAQ: https://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Categorías
Más información sobre Introduction to Installation and Licensing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!