bug in find function

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?

Answers (2)

Stephen23
Stephen23 on 16 Oct 2018
Edited: Stephen23 on 16 Oct 2018
"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.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:

3 Comments

thx! But how would you do it in my both ways? I have to do it inside a big script and I dont know how to do it.
Try this:
a = [-1:0.01:1];
n1 = find(ismembertol(a,-0.93))
n2 = find(ismembertol(a,-1+0.07))
n1 =
8
n2 =
8
>>
thx!!
it was very helpful!

Sign in to comment.

Categories

Asked:

on 16 Oct 2018

Answered:

on 16 Oct 2018

Community Treasure Hunt

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

Start Hunting!