Path: news.mathworks.com!not-for-mail 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$1@newscl01ah.mathworks.com> References: <j7sh2e$q77$1@newscl01ah.mathworks.com> Reply-To: <HIDDEN> NNTP-Posting-Host: www-03-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: newscl01ah.mathworks.com 1319252955 19109 172.30.248.48 (22 Oct 2011 03:09:15 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Sat, 22 Oct 2011 03:09:15 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 1187260 Xref: news.mathworks.com comp.soft-sys.matlab:746752 "Julio Gonzalez" <julio@part-time-scientists.com> wrote in message <j7sh2e$q77$1@newscl01ah.mathworks.com>... > ...... > 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