Path: news.mathworks.com!newsfeed-00.mathworks.com!news.tele.dk!feed118.news.tele.dk!feed116.news.tele.dk!bofh.vszbr.cz!news.radio.cz!newsreader4.netcologne.de!news.netcologne.de!feeder.news-service.com!aioe.org!.POSTED!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: While loop fails
Date: Sat, 22 Oct 2011 13:06:23 -0500
Organization: Aioe.org NNTP Server
Lines: 48
Message-ID: <j7v0n2$qof$1@speranza.aioe.org>
References: <j7sh2e$q77$1@newscl01ah.mathworks.com> <j7siql$37t$1@newscl01ah.mathworks.com> <j7t5fi$53$1@newscl01ah.mathworks.com>
NNTP-Posting-Host: CvpAmU06WO/KsZZgBIfwxQ.user.speranza.aioe.org
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Complaints-To: abuse@aioe.org
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.18) Gecko/20110616 Thunderbird/3.1.11
X-Notice: Filtered by postfilter v. 0.8.2
Xref: news.mathworks.com comp.soft-sys.matlab:746793

On 10/21/2011 8:15 PM, Julio Gonzalez wrote:
...

> It is a simple while loop. T is integer equal to 2;  ...

no, No, NO!!!

T is a (Matlab default) double which _contains_ an integral value of 2.

Insert

whos T

after the line T=2 if you don't believe it.

> ... "to" increments 0.1
> on each pass of the loop until it reaches 2.0. It works while (to<2).
> But it fails in the checking when to = T = 2.
> If I print T, I can see only the number "2"... No decimal point.
> I can not make T double even if I explicitly makes it double. But if I
> apply T = 2*(1+eps) then I can see now T= 2.0000 and the while loop
> terminates correctly...

This depends on your definition of "correctly".

Use

format long

to see the long value of any intermediate values (or display the values 
of t0-2 to amplify the floating point remainder).

As another respondent said, the "problem" is one of floating point 
precision and the use of t+dt is the most error-accumulating way one can 
possibly find to compute a running total; if dt is under the exact value 
by one bit, that one bit short will accumulate every iteration through. 
  OTOH, if you were to compute the time as t=n*dt, the error would 
average out.

Try the two following examples at the command line...

x=0;for idx=1:10000,x=x+0.1;end, x-1000

and for comparison

x=0;for idx=1:10001,x=(idx-1)*0.1;end, x-1000

--