Path: utzoo!utgpu!water!watmath!dalcs!aucs!850347s From: 850347s@aucs.UUCP (Hume Smith) Newsgroups: comp.lang.c Subject: Re: How not to write a loop Keywords: For Loops Silliness Why Message-ID: <928@aucs.UUCP> Date: 9 Mar 88 03:11:24 GMT References: <560@naucse.UUCP> <1988Feb11.200149.25172@sq.uucp> <2115@bsu-cs.UUCP> <832@unmvax.unm.edu> <712@cresswell.quintus.UUCP> Reply-To: 850347s@aucs.UUCP (Hume Smith) Distribution: na Organization: Honours Math, Acadia Univ Lines: 40 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