フィルターのクリア

Problem with equating for loop index to a variable.

1 回表示 (過去 30 日間)
Jake G
Jake G 2016 年 5 月 13 日
コメント済み: Roger Stafford 2016 年 5 月 14 日
I run the following code and it does not produce the expected results:
% code
clear all
FlowRate=0.6;
for ThermalImpCurve = 0.2:0.2:1.6
if FlowRate==ThermalImpCurve
ThermalImpCurve
break;
end
end
if the variable FlowRate is 0.6 or 1.4 the loop does not break.
  1 件のコメント

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

採用された回答

Roger Stafford
Roger Stafford 2016 年 5 月 13 日
You should read Cleve Moler's document on the subject at
http://www.mathworks.com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf
The trouble in this particular example is that binary floating point numbers are incapable of being exactly equal to values such as 0.6 or 1.4, so matlab must approximate these values. As it happens, its approximation for the original ‘FlowRate’ is slightly different from that generated by the colon operator in ThermalImpCurve, hence the failure to recognize your intended equalities. You should not demand exact equality in such situations but allow tiny error tolerances.
  2 件のコメント
Jake G
Jake G 2016 年 5 月 13 日
Thank you! That was very helpful
Roger Stafford
Roger Stafford 2016 年 5 月 14 日
To add to the discussion above, here are the two differing binary representations of 0.6 . FlowRate=0.6 in matlab’s binary double is actually represented by:
0.10011001100110011001100110011001100110011001100110011
whereas ThermalImpCurve = 0.2:0.2:1.6 at the third element is represented by:
0.10011001100110011001100110011001100110011001100110100
As you can see, they differ only by 1 in the least bit out of 53 bits. Neither value is exactly 0.6, which would require infinitely many binary digits. FlowRate is rounded down, whereas ThermalImpCurve(3) was rounded up and is a bit farther off the correct value. This latter is probably due to the fact that the 0.2 increment itself in ThermalImpCurve cannot be exactly represented and so there is possibly a cumulative effect.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by