Path: utzoo!mnetor!uunet!lll-winken!lll-lcc!ames!hao!gatech!gtss!chas From: chas@gtss.UUCP (Charles Cleveland) Newsgroups: comp.lang.c Subject: Re: How not to write a loop Message-ID: <202@gtss.UUCP> Date: 1 Mar 88 15:46:28 GMT References: <560@naucse.UUCP> <1988Feb11.200149.25172@sq.uucp> <2115@bsu-cs.UUCP> <296@draken.nada.kth.se> <832@unmvax.unm.edu> <7384@brl-smoke.ARPA> Reply-To: chas@gtss.UUCP (Charles Cleveland) Organization: Georgia Tech School of Physics Lines: 49 Keywords: For Loops Silliness Why Summary: So why wouldn't everyone always use ints? In article <7384@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) writes: >In article <832@unmvax.unm.edu> mike@turing.UNM.EDU.UUCP (Michael I. Bushnell) writes: >> float x; >> for (x = 0; x < 20; x += .5) >> printf("%f\n", x); >>The output would, of course, be >> 0.0 > ... >> 19.5 > >and, perhaps, > 20.0 >(ignoring the nit that this isn't quite the format specified). > >That is why the original poster didn't want to see such loop control >in putative portable programs. Which is why the original loop, given that floats were going to be used, should have been written in the (portable) way that follows: float x; for (x = 0; x < 20-.25; x+= .5) printf("%f\n",x); This is just a matter of subtracting half the increment from the (to be excluded) upper limit. Not that this is a general solution. Perhaps we should write something like #define min(x,y) = (x < y ? x : y) float x, start=0, end=20, inc=.5, shift; shift=.5*min(end-start,inc); for (x = start; x < end-shift; x += inc) printf("%f\n",x); What a disgusting mess. Why not use ints, and avoid all this convolution? Because the convolution may be unavoidable. This doesn't really have to do with loops and portability, but with the fact that round-off errors make tests for equality between floating point numbers unreliable. We don't need two machines to get problems -- one machine and two sets of numbers to compare will suffice. If the condition you need to impose is intrinsically a floating point condition then you may have to think hard about how to code it so that round-off can't cause problems. If you do this right, the code will likely be portable across machines as well. But if your job is to write a program to print all the integers and half-integers between 0 and 19.5 inclusively, use ints. ;-) -- -Life would be so much easier if we could just look at the source code.- Charles Cleveland Georgia Tech School of Physics Atlanta, GA 30332 UUCP: ...!gatech!gtss!chas INTERNET: chas@ss.physics.gatech.edu