I have this code which is behaving differently for decimal and integer values. Where am I missing??

x=0.1;
y=0.1;
a=[x,y];
b=[0.2,0.2];
tf=isequal(a,b);
while tf==0
x=x+(0.01);
y=y+(0.01);
a=[x,y];
tf=isequal(a,b);
end
disp(a);
if i replace the x, y and incremental values by integers, it works !! for ex as shown below
x=1000;
y=1000;
a=[x,y];
b=[2000,2000];
tf=isequal(a,b);
while tf==0
x=x+1;
y=y+1;
a=[x,y];
tf=isequal(a,b);
end
disp(a);

5 件のコメント

Paolo
Paolo 2018 年 5 月 31 日
編集済み: Paolo 2018 年 5 月 31 日
EDIT: See Stephen's answer below.
A possible workaround is to convert the floating point numbers to characters to compare them:
tf=(isequal(sprintf('%c',a),sprintf('%c',b)));
dpb
dpb 2018 年 5 月 31 日
See What Every Computer Scientist Should Know regarding floating point arithmetic
Stephen23
Stephen23 2018 年 5 月 31 日
編集済み: Stephen23 2018 年 5 月 31 日
See my answer to know how the accumulated floating-point error means that those values are NOT the same.
Paolo
Paolo 2018 年 5 月 31 日
Thanks for the clarification Stephen, I forgot to take into consideration the accumulating error.
akash sonnad
akash sonnad 2018 年 5 月 31 日
Thank you Stephen Cobeldick !!

サインインしてコメントする。

 採用された回答

"That is really weird indeed. Perhaps MATLAB struggles to determine equality for floating point numbers"
Not at all: if two numbers are really equal, then MATLAB will correctly identify them as such. The only struggle here is beginners who believe that 0.1 is really stored in their computer, and have yet to learn that floating point number errors accumulate through all computations. Which means that those numbers are NOT equal.
"Where am I missing??"
Never use == to test for equivalence of decimal values. Always compare the difference against a tolerance:
abs(A-B)<tol
You need to learn about the practical limits of floating point numbers:
And some external links on this topic:
The solution is always the same, as shown in all of those links: compare the absolute difference against a tolerance, like this:
abs(A-B)<tol
Methods to be avoided: converting to string is very slow, and rounding the values introduces artifacts that do not exist in the data.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

質問済み:

2018 年 5 月 31 日

編集済み:

2018 年 5 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by