weird results with relational operation ==

1 view (last 30 days)
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

Accepted Answer

Anton Semechko
Anton Semechko on 26 Jun 2012
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 Comments
Edward
Edward on 26 Jun 2012
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 on 26 Jun 2012
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.

Sign in to comment.

More Answers (1)

kjetil87
kjetil87 on 26 Jun 2012
isequal(xchk,X3)
ans =
0
isequal(xchk, round(1000*X3)/1000 )
ans =
1

Community Treasure Hunt

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

Start Hunting!