"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in
message news:kbqd0b$e6t$1@newscl01ah.mathworks.com...
> "Xing Li" <xli71@syr.edu> wrote in message
> <kbqar0$7co$1@newscl01ah.mathworks.com>...
>> I have a very simple while loop, which was supposed to break right away
>> until n = 10. But this loop never break because n = 10.1 in the end. How
>> could this happened? n = 0;
>> flag = 0;
>> while (flag == 0)
>> if( n < 10)
>> n = n + 0.1;
>> if(n == 10)
>> flag = 1;
>> end
>> end
>> end
>           
>
> The reason is that your computer is using binary floating point to
> represent its numbers and can't get an exact expression for 0.1 .
> Consequently when you add it a hundred times you may not get an exact sum
> of 10 because of that tiny error. In such a situation you shouldn't be
> using the "==" operator. Use some other counting technique or allow some
> some tolerance for small errors.
Or scale.
tenN = 0;
flag = 0;
while ~flag
if tenN < 100
tenN = tenN + 1;
if tenN == 100
flag = 1;
end
end
end
If you need to do something with n in the WHILE loop, n is tenN/10 (although
unless tenN is a multiple of 5 this too will not be exactly representable.)
Of course there are other ways to implement this in an IMO more
straightforward manner (FOR loop, for example) but since this feels like an
exercise for an introductory MATLAB or programming class, perhaps its
purpose was to teach WHILE loops.

Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
