Path: utzoo!attcan!uunet!ogicse!ucsd!ucselx!petunia!news From: rcfische@polyslo.CalPoly.EDU (Ray Fischer) Newsgroups: comp.sys.mac.programmer Subject: Re: Why can't the Mac add? Message-ID: <26fc2801.6f3@petunia.CalPoly.EDU> Date: 23 Sep 90 03:12:01 GMT References: <45060@apple.Apple.COM> <4485@sage.cc.purdue.edu> Organization: Cal Poly State Univ,CSC Dept,San Luis Obispo,CA 93407 Lines: 39 ar4@sage.cc.purdue.edu (Piper Keairnes) writes ... >In <45060@apple.Apple.COM> das@Apple.COM (David Shayer) writes: > >>I was running this simple program. > >>main () >>{ >> float x; >> >> for (x=0.0;x!=10.0;x+=0.2) >> printf ("x=%f \n",x); >>} > >That isn't that simple of a program when dealing with floating point >numbers. There is no such thing as an EXACT floating point number. Floating >point numbers are close approximations to real numbers. In Mathematics, real Actually, all the answers I've read do not give the correct answer to this question. And so, why doesn't the loop end? Well ... In fact, precision has nothing to do with the problem. The reason that the loop won't terminate is that 0.2 cannot be represented exactly in base-2, just as 1/3 cannot be represented exactly in base-10. You end up with a repeating decimal (or binary) fraction. In decimal 1/3 turns into a repeating 0.33333 and in binary 0.2 turns into a repeating 0.00110011001100. Just as adding 0.33333 30 times will never equal 10, adding 0.2 50 times will never equal 10 in binary, no matter what precision you use. Although many floating point numbers ARE exact (0.125 for example), some cannot be, which is why testing for equality using floating point numbers is always dicey at best. The correct loop would start ... for (x = 0.0; x < 10.0; x += 0.2) Ray Fischer rcfische@polyslo.calpoly.edu