Can someone please explain why the comparison result comes out false for this code?
-----------------------------------------------------------
Node.active_time=1;
temp=0.5;
%through some iterations temp increases. Lets hard code it here
temp=temp+0.1;
temp=temp+0.1;
temp=temp+0.1;
temp=temp+0.1;
temp=temp+0.1;
%by now value of temp is 1.0000
temp==Node.active_time
----------------------------------------------------------------
Matlab answers 0 for this, which means they are not equal. Why?
However, if we manually assign values and then compare them, it agrees with comparision. For example,
temp=1.0000;
Node.active_time=1;
temp==Node.active_time
matlab's answer to this is 1, which means they are equal (rightly so).
Why is it that comparison in previous code shows false?

 採用された回答

James Tursa
James Tursa 2013 年 7 月 10 日
編集済み: James Tursa 2013 年 7 月 10 日

0 投票

Floating point operation limitations. E.g., see here
In your particular case, 0.1 cannot be represented exactly in IEEE double floating point arithmetic, leading to the differences you are seeing.
For floating point comparisons you generally need to use a tolerance, e.g.,
abs(temp-Node.active_time) < tol

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by