Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!texsun!texsun.central-relay.sun.com!convex!authorplaceholder From: cuddy@convex.UUCP Newsgroups: comp.lang.c Subject: Re: How not to write a loop Message-ID: <64400004@convex> Date: 1 Mar 88 20:11:00 GMT References: <296@draken.nada.kth.se> Lines: 60 Nf-ID: #R:draken.nada.kth.se:-29600:convex:64400004:000:2260 Nf-From: convex.UUCP!cuddy Mar 1 14:11:00 1988 ok@quintus.Sun.COM (our feed trashes addreesses, that may not be right!) > 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 > > Quite right, there is nothing in K&R (or dpANS) to prohibit this. > But you have provided a good illustration of why people disparage > the use of floating-point variables in loop control. > THERE IS NO "OF COURSE" ABOUT THAT OUTPUT! > > You should not be surprised to see as the last value > 19.99999 Only if you declare things as floats! !! (from K&R: 2.4.4, pg. 181 !! A floating constant consists of an integer part . . . !! . . . may be missing. Every floating constant is taken to be a double. !! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ every "C" compiler (at least ones that conform to K&R) will cast floats to doubles and sometimes they have troubles. this has to do with your compiler and machine. the above program segment ( for(x=0; x< 20; x+=5)... ) should probably be written: double x; ^^^^^^ this will help you not get round off errors for (x = 0.0; x < 20.0; x += 0.5) printf("%f\n",x); ^^^ ^^^^ ^^^ these don't have to be this way, but i've allways felt it good programming practice. > THERE IS NO "OF COURSE" ABOUT THAT OUTPUT! There's lots of "of course"s about "C" and that output if it's done right! > 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 more float-double round off error. This kind of thing bites you when you use the -lm libraries without #including . ------------------------------------------------------------------------------ The opinions stated above are barely my own, how can they be of my employers? Mike Cuddy, CONVEX Computer Corporation 701 N. Plano Rd. Richardson, TX 75081 uucp:{uiucdcs,ihnp4,sun,allegra}!convex!cuddy ------------------------------------------------------------------------------