"for" loops (was Re: C++ vs. Modula

flint at gistdev.UUCP flint at gistdev.UUCP
Sat Feb 4 07:14:00 AEST 1989


/* Written 10:02 am  Feb  2, 1989 by atanasoff.cs.iastate.edu!hascall in gistdev:comp.lang.c */
In article <7800002 at gistdev> flint at gistdev.UUCP writes:

 How's it supposed to know to use 10? 
 When I do 1.0/0.1, I get 9.99999985...  Well, it's pretty close to 10,
 let's use that :-)

I guess it is obvious to me, not to others: If the increment that the user
wrote was 0.1, with one digit to the right of the decimal point, the
compiler should obviously use 10 as the denominator because 0.1 = 1/10.  If
the user wrote a loop that incremented by 0.127, the compiler writer should
use 1000 for the divisor, because the user had 3 digits to the right of the
decimal.   Any increment the user can type into their program can be exactly
represented as a fraction unless the compiler is stupid enough to throw
the information away.  (IE, they use PI for the increment: where did you
get PI?  Someplace had a #define  PI 3.1415926.  If the user gave you
7 digits of precision, use 10 ** 7 as the divisor that gives the floating
point value you need.)

It should be noted that I advocated doing this to "simple" loops where it
works, not to every loop.  In the
    do 10 i=0,1,0.1
case, you can KNOW to run this loop exactly 11 times: but not if you stupidly
try to divide 1/0.1 with binary based arithmetic, where it might round to a
result less than 10.  Your user wrote the loop in decimal, and in decimal the
arithmetic produces an exact result.  Think the math is too complex a task
for your compiler to do?  Then try this simple trick:
What the programmer wrote in their code:             do  10 i=2.5,3.75,0.25
Move the decimal points in the text 2 places right:  do  10 i=250,375,25
(Manipulate the text string if you feel the need.)
Bingo, you've got an integer loop, you know to get the floating loop
index you divide by (10 ** 2) or 100 (because you slid the decimal places
2 positions in order to get rid of all the digits right of the decimal
points.)  Note that in some loops, where i isn't even used in the body of
the loop, you can dispense with the floating point altogether now.

You can certainly argue that doing the above won't protect you in every
single case, and you're right, it won't.  But that sounds to me a lot like
arguing that you shouldn't have optimizers because they might change the
code to not be exactly what the programmer wrote.  I believe that in all
the examples presented so far you do know exactly what the programmer wanted
you to do.

Flint Pellett, Global Information Systems Technology, Inc.
1800 Woodfield Drive, Savoy, IL  61874     (217) 352-1165
INTERNET: flint%gistdev at uxc.cso.uiuc.edu
UUCP:     {uunet,pur-ee,convex}!uiucuxc!gistdev!flint



More information about the Comp.lang.c mailing list