From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: While loop fails
Date: Sat, 22 Oct 2011 03:09:15 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 12
Message-ID: <j7tc4r$il5$>
References: <j7sh2e$q77$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1319252955 19109 (22 Oct 2011 03:09:15 GMT)
NNTP-Posting-Date: Sat, 22 Oct 2011 03:09:15 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:746752

"Julio Gonzalez" <> wrote in message <j7sh2e$q77$>...
> ......
>     to = to+0.1;
> ......
- - - - - - - -
  Julio, after twenty executions of the line

 to = to+0.1;

starting with 'to' equal to zero, the value of 'to' will not be an exact 2.0, but rather 2+2^(-51), which is greater than 2 by a very tiny amount.  You can use 'format hex' to show this.  Does this explain things?  This error is caused by the fact that a binary floating point number cannot be exactly equal to 0.1 = 1/10 for just the same reason that decimal fractions can never be exactly equal to 1/3.  After twenty additions by this slightly erroneous value it is only in excess of an exact 2.0 by one bit at its least significant end, but that is presumably enough to cause trouble with the method you are using in your loop.  You need to alter your method, perhaps by counting with integers.

Roger Stafford