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?
回答(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 个评论
Benzy Laufer
2018-10-16
Bruno Luong
2018-10-16
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
2018-10-16
Image Analyst
2018-10-16
0 个投票
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
类别
在 帮助中心 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!