MATLAB: While loop causing an infinite loop in MATLAB

binary floating pointdoublefloating point error.floating point numbersinfiniteinfinite looploopsMATLABsumwhilewhile loop

Hi everyone,
I'm new to computer science and coding in general, so I apologize if this seems like a silly question.
I have a piece of code that involves a while loop which enters an infinite loop. I suspect it has something to do on line five, as when I change the value 0.1 to 1, the code is properly executed. I've attempted to rewrite the code using other loops, but to no avail.
Can I get an explanation as to why the code is entering this infinite loop? Thank you!
s=0
while s ~=5
s = s + 0.1;
end

Best Answer

"Can I get an explanation as to why the code is entering this infinite loop?"
Of course, it is very simple: you are using a computer which stores values as binary floating point numbers. In exactly the same way that you cannot write 1/3 exactly using a finite decimal fraction, it is impossible to store 0.1 exactly using a finite binary floating point number. So although you might think that you have 0.1, in fact the real values stored in computer memory is slightly different from this. And so when you add them, it collects this floating point error, so that the final total is never exactly equal to 5.
The simplest solution for your code is to use while s<5.
What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that that number does not really have the exact value 0.1. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.1 displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well: