Path: utzoo!attcan!uunet!lll-winken!sun-barr!cs.utexas.edu!radar!banach!mishra From: mishra@banach.ACA.MCC.COM (Aditya Mishra) Newsgroups: comp.lang.c Subject: floating point multiplication BUG in C (cc compiler) Keywords: bug in C float multiplication Message-ID: <1348@banach.ACA.MCC.COM> Date: 19 Oct 90 19:16:22 GMT Organization: MCC Human-Interface Lines: 66 BUG !!! BUG !!! BUG !!! THIS PROGRAM DEMONSTRATES WHAT I BELIEVE IS A BUG IN FLOATING POINT MULTIPLICATION IN 'C' !! I ACCIDENTALLY STUMBLED ON A PATTERN OF FLOATING POINT OPERAND VALUES FOR WHICH RESULTS ARE QUITE INACCURATE !!! I WAS GETTING UNDESIRED BEHAVIOR IN A PROGRAM BECAUSE OF THIS (APPARENT) BUG. I FELT IT MIGHT BE SERIOUS AND IMPORTANT TO ALL C USERS. bug.c ----- Aditya Mishra, MCC Austin (512) 338 3481 ----------------------------------------- (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. This error was absent if the value of f was not from the above pattern (if f = 0.65, e. g.). (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. (3) These bugs persist on cc (C compiler) on about six machines that I could get my hands on. (4) I am not sure if this is really a bug. I am just expressing an experience that teaches me to be careful with floating point results of multiplication. */ /*-- -- -- -- -- -- --*/ #include main() { int i1, i2; float r1, r2; float g = 9.0025; float f = 0.32; float factor = 10000.0; i1 = factor * f; /* *even if* i = (int) (factor * f); */ r1 = factor * f; i2 = factor * g; /* *even if* i = (int) (factor * g); */ r2 = factor * g; printf("%d ", i1); printf("%f \n", r1); printf("%d ", i2); printf("%f \n", r2); } /*-- -- -- -- -- -- --*/