필터 지우기
필터 지우기

weird results with relational operation ==

조회 수: 3 (최근 30일)
Edward
Edward 2012년 6월 26일
Hi all,
I got very weird responses from Matlab with the following extremely simple code. For the first if statement, xchk == X3 should be true, however Matlab surprisingly thinks it is false! The second if statement works normally. I really can't understand this, could anyone please help me out from this? Thank you!!
clear;
h = 230/1000;
b = 240/1000;
s = 7.5/1000;
t = 12/1000;
X1 = -t;
X2 = 0.0;
X3 = h - 2*t;
X4 = h - t;
Y1 = (b-s)/2;
Y2 = b/2;
xchk = 0.2060;
ychk = 0.0;
if xchk == X3
tt = 1;
end
if ychk < Y1
tt = 2;
end
if (xchk == 0 && ychk < Y1)
tt = 3;
end

채택된 답변

Anton Semechko
Anton Semechko 2012년 6월 26일
The expression xchk == X3 is indeed false, however , if you check the value of abs(xchk-X3) you will find it to be less than machine precision. Since you are dealing with floating point representations, a more robust way of checking the equality of two scalar quantities, A and B, would be
abs(A-B)<tol
where 'tol' is some tolerance parameter (e.g. tol=eps)
  댓글 수: 2
Edward
Edward 2012년 6월 26일
Thanks Anton! I understand it now. It seems other language such as C++ could compare the equality of two float quantities directly, without checking the absolute value of the difference..
Walter Roberson
Walter Roberson 2012년 6월 26일
No no! Do not directly compare [finite precision] floating point numbers for equality in *any* programming language. Round-off problems exist in EVERY numeric system that uses finite storage.
C++ is very definitely included. You have exactly the same problems in C++.
The main (but subtle) difference with MATLAB is that the internal workings of sum() and the colon operator are not specified, allowing different results. With sufficiently large arrays, sum() will end up calling out to a multi-threaded library routine, thus giving back results that differ from a purely sequential "a += b[k]" type summation.
Also, when the "accel" feature is on (which it is by default), the relative order of operations in loops is not specified. C++ has its sequence points that define the order of operations. On the other hand, the very very common optimization options you can (and probably do) give to C++ compilers often override that part of the C++ standard.

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

추가 답변 (1개)

kjetil87
kjetil87 2012년 6월 26일
isequal(xchk,X3)
ans =
0
isequal(xchk, round(1000*X3)/1000 )
ans =
1

카테고리

Help CenterFile Exchange에서 Use Prebuilt MATLAB Interface to C++ Library에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by