one problem about ismember function

조회 수: 11 (최근 30일)
Lin Yang
Lin Yang 2018년 7월 10일
댓글: Steven Lord 2018년 7월 10일
Hi, everyone, when I'm using ismemeber function, something goes wrong:
A=0.2:0.2:20;
B=5:5:20;
for i=1:100
if ismember(A(i),B)
disp(i)
end
end
it should display i = 25,50,75 and 100; but it only display 50,75,and 100;
Can anyone tell me why? Many thanks.

채택된 답변

OCDER
OCDER 2018년 7월 10일
편집: OCDER 2018년 7월 10일
This isn't an issue with ismember but with floating point math in general. Computers can't always add and subtract floating point number precisely, which introduces some rounding errors. Thus, when using "==" or ismember to compare floating point numbers, you run into issues.
Read the example for "Comparing Floating Point Numbers" at https://www.mathworks.com/help/matlab/ref/eq.html
C = 0.5-0.4-0.1
%Should be mathematically equal to 0, right? NOPE! returns -2.7756e-17.
C == 0
Equality returns false.
ismember(C, 0)
ismember returns false.
To fix, you have to see if the values are close enough via some sort of tolerance level.
abs(C-0) < 1E-15
Inequality returns true. C is close enough to 0 to be considered 0.
In your case, don't use ismember. Instead do something like:
A=0.2:0.2:20;
B=5:5:20;
for i=1:100
if any(abs(A(i)-B) < 1E-15)
disp(i)
end
end
  댓글 수: 1
Steven Lord
Steven Lord 2018년 7월 10일
Consider using ismembertol instead of ismember.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sayyed Ahmad
Sayyed Ahmad 2018년 7월 10일
That is not a problem of ismember function. The machine accuracy is in matlab eps
>>eps
ans=
2.2204e-16
to better understand you have to try this
>> 5==5+2*eps
ans =
logical
1
>> 5==5-2*eps
ans =
logical
1
I IEEE Standard “double precision floating point” is eps ≈ 1.11 × 10−16. In matlab the eps is 2^-52 but as you see +2*eps or less 2*eps deliverd the same resault.
in your case A(25)-5 is equal 4*eps which is numeric precision of calculation for 0.2:0.2:20.
If you use the diffrent of values (A(25)-5)<=4*eps the answer will be logical true.
I hope that is the answer of your quastion.
Cheers
Ahmad

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by