Path: news.mathworks.com!not-for-mail From: <HIDDEN> Newsgroups: comp.soft-sys.matlab Subject: Re: A bug with integers Date: Wed, 4 Aug 2010 05:24:04 +0000 (UTC) Organization: The MathWorks, Inc. Lines: 32 Message-ID: <i3athj$o40$1@fred.mathworks.com> References: <i3ap98$qpm$1@fred.mathworks.com> Reply-To: <HIDDEN> NNTP-Posting-Host: webapp-05-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: fred.mathworks.com 1280899444 24704 172.30.248.35 (4 Aug 2010 05:24:04 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Wed, 4 Aug 2010 05:24:04 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 1187260 Xref: news.mathworks.com comp.soft-sys.matlab:658878 "Dinesh Bhati" <bhatidinesh@gmail.com> wrote in message <i3ap98$qpm$1@fred.mathworks.com>... > Please run the following script and observe the bug in ver 7.5.0.342(R2007b) > clear > clc > t=0:1/50000:0.03; > disp('Following script is able to catch the integer 27'); > for i =1:length(t) > > n=t(i)*1000; > if n> 26.96 && n < 27.04 > n > if (floor(n)==ceil(n)) disp(n); > end;end; > end; > > disp('But this script is not able to catch the integer 28? IS IT A BUG IN MATLAB'); > for i =1:length(t) > > n=t(i)*1000; > if n> 27.96 && n < 28.04 > n > if (floor(n)==ceil(n)) disp(n); > end;end; > end; - - - - - - - - - - As has been pointed out numerous, numerous times in this group, modern large digital computers (rather than hand calculators) almost always use binary arithmetic, which means that they cannot make exact computations with the majority of decimal fractions. In your case matlab can express neither 1/50000 nor 0.03 exactly. When you multiply your t(i) by 1000 even when t(i) is supposedly (but not actually) equal to .027 it will not result in an exact 27. If you were using a decimal computer your code would succeed for this, but what if you asked for t=0:1/3:10000? Even the decimal machine would then fail frequently on such a test because it could not express 1/3 exactly. You will soon learn that you must not ask for exact equality as you did with floor(n)==ceil(n) in such situations as this. Roger Stafford