How not to write a loop
cuddy at convex.UUCP
cuddy at convex.UUCP
Wed Mar 2 06:11:00 AEST 1988
ok at quintus.Sun.COM (our feed trashes addreesses, that may not be right!)
> In article <832 at unmvax.unm.edu>, mike at 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 <math.h>.
------------------------------------------------------------------------------
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
------------------------------------------------------------------------------
More information about the Comp.lang.c
mailing list