"for" loops (was Re: C++ vs. Modula2)

Jim Giles jlg at lanl.gov
Sat Jan 28 11:02:21 AEST 1989


>From article <19579 at agate.BERKELEY.EDU>, by bowles at eris.berkeley.edu (Jeff A. Bowles):
> [...] 
> 1. It's not restrictive on the types of the indices, because it defines a
>    more general construct. If I had a nickel for every time, in Fortran,
>    that I needed a loop that ran from 0.0 to 1.0 by 0.1 (or the like) and
>    had to use INTEGER to do it. Or Pascal, which lacked the "step" clause
>    so that you couldn't increment by more than what the language-designer
>    wanted.
> [...] 
> 	Jeff Bowles

ALL standard conforming Fortran processors allow the following:

      DO 10 i=0.0,1.0,0.1

The standard committee now considers this to be a mistake and is likely
to remove it in 8x, but for the moment this is a standard feature.

It is considered a mistake because the standard doesn't make any
constraints on the accuracy of floating-point arithmetic.  So the
trip count on a loop with floating-point limits is not well-defined.
The C for-loop is even worse in this regard - the trip count is not
precomputed.  Consider the following:

      for (x=0.0; x<=1.0, x+=0.1) {...}

The value of x for each trip through the loop is a sum of 0.1+ ... +0.1,
a value which suffers round-off or truncation on each successive add.  
If the four operations in the computation of the Fortran trip count
lead to ambiguous results, the 11 adds in the above are even worse.
For a loop from 0.0 to 1000.0 by 0.01 on a 32-bit floating-point machine,
the round-off of the last 100 adds is comparable to the increment itself!
This may be another reason for the undesireable feature in C of assuming
double precision as the default floating-point.

J. Giles



More information about the Comp.lang.c mailing list