floating point multiplication BUG in C (cc compiler)
Henry Spencer
henry at zoo.toronto.edu
Sun Oct 21 09:17:26 AEST 1990
In article <1348 at banach.ACA.MCC.COM> mishra at banach.ACA.MCC.COM (Aditya Mishra) writes:
>THIS PROGRAM DEMONSTRATES WHAT I BELIEVE IS A BUG IN FLOATING POINT
>MULTIPLICATION IN 'C' !!
There is no bug. You have discovered the joys of floating-point arithmetic.
>(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.
Note that float->int conversion truncates, while %f conversion rounds.
You have come across boundary cases where this makes a difference, I'd
say. Look hard and you will probably find more.
>(2) Also, if float g = 1.0025, 1.32 or 9.0025 and some more values,
> the result in float r2
> (r2 = factor * g) was wrong after 2 or 3 decimal places.
Wrong after the decimal point, you mean? If so, no surprise: `float',
as opposed to `double', often only has about seven digits of precision.
In general, you should use `double' for all floating-point arithmetic
you care about, unless speed or storage is critical and you have done
a careful analysis of the tradeoffs involved.
--
The type syntax for C is essentially | Henry Spencer at U of Toronto Zoology
unparsable. --Rob Pike | henry at zoo.toronto.edu utzoo!henry
More information about the Comp.lang.c
mailing list