if statement inside a for loop not working

Hi all,
Can someone please explain why this code is not working?
for a = 0.1:0.1:5
if a == 3
b = 1;
end
end
Once 'a' becomes 3, 'b' should be assigned a 1. But nothing happens.. Not sure what is going on

 採用された回答

Adam
Adam 2016 年 10 月 5 日

0 投票

The representation of the results of floating point maths is not 100% accurate so you should never do a straight == between a number created via floating point maths and some other number. Always test within a tolerance.

3 件のコメント

van4
van4 2016 年 10 月 5 日
Thank you very much. It's a bit strange to think that even though I'm incrementing by exactly 0.1, it is not in fact "exactly 0.1".
Jos (10584)
Jos (10584) 2016 年 10 月 5 日
Welcome to the world of computers using a limited amount of bits to represent numbers!
fprintf('%.40f\n', 0.1)
van4
van4 2016 年 10 月 5 日
point taken :)

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

その他の回答 (0 件)

カテゴリ

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

タグ

質問済み:

2016 年 10 月 5 日

コメント済み:

2016 年 10 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by