floating point multiplication BUG in C (cc compiler)
Richard A. O'Keefe
ok at goanna.cs.rmit.oz.au
Mon Oct 22 11:19:42 AEST 1990
In article <1348 at banach.ACA.MCC.COM>, mishra at banach.ACA.MCC.COM (Aditya Mishra) writes:
> BUG !!! BUG !!! BUG !!!
> THIS PROGRAM DEMONSTRATES WHAT I BELIEVE IS A BUG IN FLOATING POINT
> MULTIPLICATION IN 'C' !!
Please take the trouble to learn something about floating point arithmetic
before screaming to the world that the sky is falling.
> (1) In the program, if float f = ... 0.64, 0.32, 0.16, 0.08, 0.04, 0.02,
> 0.01, 0.005, 0.0025, ..., etc (see the pattern?), the value
> of i1 was one less than what it should be.
[where i1 is calculated as
float f = /* as above */;
float factor = 10000.0;
int i1 = factor * f;
]
The problem here is that a number like 0.64 *CANNOT* *POSSIBLY* be
represented exactly in (finite-precision) floating-point. At all.
In *any* programming language. Any compiler, any string->fp converter,
is going to have to round nearly every number there is (only numbers
which are an integer times a power of 2 are likely to be exact); some
of them will round up and some of them will round down. If it rounds
down, i1 will be 1 less than you expected. If it rounds up, because
floating pointer->integer conversion truncates towards zero, the error
will be zapped away by the conversion.
2nd year CS students here know about this...
One of the things I really like about C is that unlike Fortran and
Pascal, it doesn't lie to the user. It doesn't make a false claim
to support "real" arithmetic. It honestly and openly admits to
'float'. Believe it: what you get is floating-point, not real.
--
Fear most of all to be in error. -- Kierkegaard, quoting Socrates.
More information about the Comp.lang.c
mailing list