Path: utzoo!mnetor!uunet!husc6!bbn!mit-eddie!bloom-beacon!tut.cis.ohio-state.edu!mailrus!nrl-cmf!cmcl2!brl-adm!adm!MAILER%ALASKA.BITNET@CUNYVM.CUNY.EDU From: MAILER%ALASKA.BITNET@CUNYVM.CUNY.EDU Newsgroups: comp.lang.c Subject: Undelivered mail Message-ID: <12266@brl-adm.ARPA> Date: 12 Mar 88 05:19:35 GMT Sender: news@brl-adm.ARPA Lines: 58 Subject: Re: How not to write a loop [Non-Deliverable: User does not exist or has never logged on] Reply-To: Info-C@BRL.ARPA Received: From UWAVM(MAILER) by ALASKA with Jnet id 6425 for SXJVK@ALASKA; Fri, 11 Mar 88 19:49 AST Received: by UWAVM (Mailer X1.25) id 4281; Fri, 11 Mar 88 20:41:13 PST Date: Wed, 9 Mar 88 03:11:24 GMT Reply-To: Info-C@BRL.ARPA Sender: Info-C List From: Hume Smith <850347s@aucs.uucp> Subject: Re: How not to write a loop Comments: To: info-c@brl-smoke.arpa To: Vic Kapella ok@quintus.UUCP (Richard A. O'Keefe) wrote in <712@cresswell.quintus.UUCP>: >In article <832@unmvax.unm.edu>, mike@turing.UNM.EDU (Michael I. Bushnell) writes: >> I see NOTHING which precludes: >> float x; >> for (x = 0; x < 20; x += .5) printf("%f\n", x); >> The output would, of course, be >> 0.0 >> 0.5 >> ... >> 19.5 > >You should not be surprised to see as the last value > 19.99999 >I just tried the very similar loop > for (x = 0; x < 21; x += .3) /* .3 divides 21 exactly */ >By analogy with your "of course", the last output should obviously >be 20.7. In fact, when I tried it just now, the last output was > 20.999994 I would be quite surprised to see 19.99999 come out in the former loop. .5 is exactly representable in floating binary, and should cause no problem as an increment. .3 is not representable in a finite binary fraction (.01001 something, it repeats eventually), and cannot be summed up to get an integral value. If the machine did its arithmetic in decimal (Texas Intstruments? Sharp?) then the .3 increment would again not be a problem, since the representation is exact again. This, however, is the point. The behaviour of a particular increment is unreliable. (Not to be insulting at all, but this may be why our Computer Science department makes its majors take our Numerical Methods Course. The very first thing we do is Machine Epsilon and roundoff error. This comment is just to make enough text to keep inews happy.) -- Hume Smith UUCP: Math Department {uunet|watmath|utai|garfield|mnetor}! Acadia U dalcs!aucs!850347s