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
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 Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

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