How not to write a loop

Charles Cleveland chas at gtss.UUCP
Wed Mar 2 01:46:28 AEST 1988


In article <7384 at brl-smoke.ARPA> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>In article <832 at unmvax.unm.edu> mike at 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 at ss.physics.gatech.edu



More information about the Comp.lang.c mailing list