Newsgroups: comp.lang.c Path: utzoo!henry From: henry@zoo.toronto.edu (Henry Spencer) Subject: Re: floating point multiplication BUG in C (cc compiler) Message-ID: <1990Oct20.231726.3249@zoo.toronto.edu> Organization: U of Toronto Zoology References: <1348@banach.ACA.MCC.COM> Date: Sat, 20 Oct 90 23:17:26 GMT In article <1348@banach.ACA.MCC.COM> mishra@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@zoo.toronto.edu utzoo!henry