weird results with relational operation ==
2 ビュー (過去 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
0 件のコメント
採用された回答
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 件のコメント
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 件)
参考
カテゴリ
Help Center および File Exchange で Arithmetic Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!