Path: news.mathworks.com!not-for-mail From: "Steven_Lord" <slord@mathworks.com> Newsgroups: comp.soft-sys.matlab Subject: Re: help for while loop Date: Sun, 30 Dec 2012 22:46:12 -0500 Organization: MathWorks Lines: 54 Message-ID: <kbr1q4$k37$1@newscl01ah.mathworks.com> References: <kbqar0$7co$1@newscl01ah.mathworks.com> <kbqd0b$e6t$1@newscl01ah.mathworks.com> NNTP-Posting-Host: ah-slord.dhcp.mathworks.com Mime-Version: 1.0 Content-Type: text/plain; format=flowed; charset="UTF-8"; reply-type=response Content-Transfer-Encoding: 7bit X-Trace: newscl01ah.mathworks.com 1356925572 20583 172.28.9.169 (31 Dec 2012 03:46:12 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Mon, 31 Dec 2012 03:46:12 +0000 (UTC) In-Reply-To: <kbqd0b$e6t$1@newscl01ah.mathworks.com> X-Priority: 3 X-MSMail-Priority: Normal Importance: Normal X-Newsreader: Microsoft Windows Live Mail 14.0.8089.726 X-MimeOLE: Produced By Microsoft MimeOLE V14.0.8089.726 Xref: news.mathworks.com comp.soft-sys.matlab:785638 "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