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!