Switch case do not evaluate to true

for HP = 0.2:0.2:1
HP
switch(HP)
case 0.2
Statement
case 0.4
Statement
case 0.6
Statement
case 0.8
Statement
case 1.0
Statement
end
end
I understand this is how it should be writen but the case 0.6 never evaluates to true. I don't know what I have done wrong.
If I change the switch expression from HP to 0.6, then the case 0.6 evaluates as true.
The HP before the switch statement produces all the values including the 0.6.

5 件のコメント

Stephen23
Stephen23 2021 年 8 月 26 日
編集済み: Stephen23 2021 年 8 月 26 日
" I don't know what I have done wrong."
You expect exact equivalence when comparing binary floating point numbers. In general that will not work.
"The HP before the switch statement produces all the values including the 0.6."
No it doesn't.
The decimal value 0.6 cannot be represented exactly using binary floating point numbers:
sprintf('%.64f',0.6)
ans = '0.5999999999999999777955395074968691915273666381835937500000000000'
Learn more about binary floating point numbers:
This is worth reading as well:
Enoch Zingbagba
Enoch Zingbagba 2021 年 8 月 26 日
@Stephen Thanks a lot, you have saved me today.
I have changed the for loop to array
for HP = [0.2 0.4 0.6 0.8 1]
This now works for me
Walter Roberson
Walter Roberson 2021 年 8 月 26 日
Strictly speaking,
[0.2 0.4 0.6 0.8 1]
the right hand side is the result of a calculation -- the [ ] around the vector are an operator. Whereas the literals in the cases are not the result of a calculation
MATLAB does not guarantee that the result of a calculation will match a literal, so really you should use ismembertol() instead of looking for an exact match.
In this particular case, the literals inside the [] are all double precision, and the [] operator would be doing bitwise copies for the case where the values are all the same datatype, so it would be able to match the literals -- but it is a bad habit to get into.
Stephen23
Stephen23 2021 年 8 月 26 日
@Enoch Zingbagba: your approach is ... not a good habit.
A much better approach would be to learn how to handle floating point numbers robustly.
Enoch Zingbagba
Enoch Zingbagba 2021 年 8 月 26 日
Ok I will learn about floating numbers. Thanks a lot.

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

回答 (0 件)

カテゴリ

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

製品

リリース

R2021a

質問済み:

2021 年 8 月 26 日

コメント済み:

2021 年 8 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by