Compare values from for loop

Hello, I just experienced something weird (at least something I wouldn't have expected):
for m=0.4:0.2:1.2
if (m == 0.6)
a = 2;
end
end
Now even if my m is assigned to 0.6 the if condition will give 0. Why is that and how can I avoid that?
Thanks, Paul

 採用された回答

Evan
Evan 2013 年 7 月 8 日
編集済み: Evan 2013 年 7 月 8 日

0 投票

It looks like this is resulting from the limited precision of floating point numbers. When you pause the execution of the loop when m should be 0.6 and type m - 0.6, you should get a very small number like 1.1102e-16. Does the following change fix your problem?
for m=0.4:0.2:1.2
if abs(m - 0.6) <= eps(0.6)
a = 2;
end
end

その他の回答 (1 件)

Paul
Paul 2013 年 7 月 8 日

0 投票

This is working.
Thank you!

1 件のコメント

Evan
Evan 2013 年 7 月 8 日
No problem! Also, if your question has been answered, be sure to click the "accept answer" button so that other users here know that the problem has been resolved.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2013 年 7 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by