Path: utzoo!attcan!uunet!samsung!ernie.viewlogic.com!hari!peter From: peter@hari.Viewlogic.COM (Peter Colby) Newsgroups: comp.sys.mac.programmer Subject: Re: Why can't the Mac add? Message-ID: <1990Sep24.120758@hari.Viewlogic.COM> Date: 24 Sep 90 16:07:58 GMT References: <45060@apple.Apple.COM> Sender: news@viewlogic.com (News Administrator) Reply-To: peter@hari.Viewlogic.COM (Peter Colby) Organization: Viewlogic Systems, Inc., Marlboro, MA Lines: 46 >main () >{ > float x; > > for (x=0.0;x!=10.0;x+=0.2) > printf ("x=%f \n",x); >} > >As you can see, it ought to stop when x==10.0. However, >it actually runs in an infinite loop. This is because >x never equals exactly 10.0. The +0.2 always makes x >equal to 9.999999 or 10.000001 or something. Changing >x from a float to a double makes x stay closer to the >correct value, but it still isn't exactly correct, and >as the loop runs longer, x gets off more and more. > >So my question is, why can't the Mac do simple math? One of the cardinal rules in floating point math is NEVER USE EXACT EQUALITY TESTS!!! Without going into a long involved explanation of how floating point works, suffice it to say that floating point is inexact. There are several issues, one of which is that the Mantissa (the actual number itself without reference to the position of the decimal point) is expressed internally as reciprocal powers of 2 (ie: 1/2 + 1/4 + 1/8 + ...). If your fraction can't be exactly expressed as some combination of these fractions WITHIN THE PRECISION OF THE SYSTEM (that is the number of bits used to hold the mantissa) then you get an approximation of the number you expect. In your case, 1/5 (0.2) is the culprit. In your particular case your best bet is to change the for statement to be: for (x=0.0;x<10.0;x+=.02) Peter C. -- (O)(O)(O)(O)(O)(O)(O)(O)(O) (O)(O)(O)(O)(O)(O)(O)(O)(O) (O) !the doctor is out! (O) (0) peter@viewlogic.com (0) (O)(O)(O)(O)(O)(O)(O)(O)(O) (O)(O)(O)(O)(O)(O)(O)(O)(O)