Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!julius.cs.uiuc.edu!apple!lins From: lins@Apple.COM (Chuck Lins) Newsgroups: comp.sys.mac.programmer Subject: Re: Why can't the Mac add? Message-ID: <45084@apple.Apple.COM> Date: 24 Sep 90 17:22:00 GMT References: <45060@apple.Apple.COM> Organization: Apple Computer Inc., Cupertino, CA Lines: 44 In article <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); >} > >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? > >Please enlighten me. Ok. I'll try :-) Real arithmetic on computer tends to be inexact. Testing for *exactly* some specific real number is a bad thing. It won't matter what hardware you use. The folks who write numerical software know this well. The proper test should be to test for almost equality with a very small epsilon. > >David > -- Chuck Lins | "Is this the kind of work you'd like to do?" Apple Computer, Inc. | -- Front 242 20525 Mariani Avenue | Internet: lins@apple.com Mail Stop 37-BD | AppleLink: LINS@applelink.apple.com Cupertino, CA 95014 | "Self-proclaimed Object Oberon Evangelist" The intersection of Apple's ideas and my ideas yields the empty set.