MATLAB: Weird results with relational operation ==

relational operation

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

Best Answer

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)