Path: utzoo!attcan!uunet!ns-mx!iowasp.physics.uiowa.edu!maverick.ksu.ksu.edu!zaphod.mps.ohio-state.edu!usc!apple!uokmax!d.cs.okstate.edu!norman From: norman@d.cs.okstate.edu (Norman Graham) Newsgroups: comp.sys.mac.programmer Subject: Re: Why can't the Mac add? Message-ID: <1990Sep23.061645.17161@d.cs.okstate.edu> Date: 23 Sep 90 06:16:45 GMT References: <45060@apple.Apple.COM> Organization: Oklahoma State University Lines: 46 From article <45060@apple.Apple.COM>, by das@Apple.COM (David Shayer): > I was running this simple program. > > 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. [...] Robert Minich sketched a solution to your problem. Now I'll describe the cause of your problem. [I'm assuming that you've asked a serious question since there weren't any smilies in your post.] Most modern computers use a base 2 number system (binary) for arithmetic rather than the base 10 system that people normally use. [Although I once heard about a Russian computer that used a base 3 number system. The only problem with it was it had to be built with flip-flap-flops rather than flip-flops.] Now, any decimal integer can be represented exactly by a finite binary integer--but this is not the case for decimal fractions. A rational decimal fraction, r, can be exactly expressed by a finite binary number only if r = p/q, where p and q are integers and q is an integer power of 2 (i.e. q = 2^n for some integer n). Your constant 0.2 clearly fails this test; thus 0.2 can be represented exactly only by an infinite string of binary digits. Since no physical computer can store and manipulate infinite strings of binary digits, you must live with a finite approximation of 0.2. This is the cause of your rounding error. I hope that's clear. --Norm -- Norman Graham {cbosgd,rutgers}!okstate!norman The opinions expressed herein do not necessarily reflect the views of the state of Oklahoma, Oklahoma State University, OSU's Department of Computer Science, or of the writer himself.