weird results with relational operation ==

4 次查看(过去 30 天)
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