Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!julius.cs.uiuc.edu!apple!uokmax!d.cs.okstate.edu!minich From: minich@d.cs.okstate.edu (Robert Minich) Newsgroups: comp.sys.mac.programmer Subject: Re: Why can't the Mac add? Message-ID: <1990Sep23.021209.14913@d.cs.okstate.edu> Date: 23 Sep 90 02:12:09 GMT References: <45060@apple.Apple.COM> Organization: Oklahoma State University Lines: 48 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. 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? | What's going on here? Is SANE insane? | | I have a Mac IIci, so I have a 68882 FPU. This program | fails in both Think and MPW C. I didn't compile with any | special FPU options on. A friend ran it on a | PC clone, and it failed in the same way there. | | Please enlighten me. | | David Unless your compiler uses arbitrary precisions math (not very darn likely), you'll probably never be happy. Binary floting point is an exercise in being close. The "correct" way to do what you want is either use integer math and fake the decimal places (ie use cents for money calculations) or use an epsilon instead of equality. #define epsilon 0.00001 for {x=0.0; x-10