Switch case do not evaluate to true
Show older comments
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 Comments
" 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)
Learn more about binary floating point numbers:
This is worth reading as well:
Enoch Zingbagba
on 26 Aug 2021
Walter Roberson
on 26 Aug 2021
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
on 26 Aug 2021
@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
on 26 Aug 2021
Answers (0)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!