How not to write a loop
Vincent Hatem
gak at mhuxm.UUCP
Sat Mar 5 08:38:28 AEST 1988
In article <64400004 at convex>, authorplaceholder at convex.UUCP writes:
>> In article <832 at unmvax.unm.edu>, mike at turing.UNM.EDU (Michael I. Bushnell) writes:
> [lots of junk I've deleted...]
>
>> 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
The errors are caused by the inherent nature of ANY IEEE floating point
number. Try it with 0.1 as an increment. It's even worse. It's all because
you simply *can't* represent the number 0.1 with IEEE floating point. You
can come very, *very*, close - but you'll still have something like
0.099999999999999 instead of 0.10000000000...
This occurs in *both* 32 and 64 bit floating point numbers, and is called
"rounding errors." The 64 bit numbers are more accurate, but they are still
off. When you printf() a floating point number, the function *rounds* the
float, then prints it.
Take a numerical methods course.
--
Vincent Hatem
AT&T International, International Systems Operations, UNIX Technical Support
Telefon: (201) 953-8030
Please send all e-mail to: ihnp4!atti01!vch
More information about the Comp.lang.c
mailing list