Path: utzoo!attcan!uunet!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: floating point multiplication BUG in C (cc compiler) Summary: not a bug in C, a misconception about floating point Keywords: bug in C float multiplication Message-ID: <4032@goanna.cs.rmit.oz.au> Date: 22 Oct 90 01:19:42 GMT References: <1348@banach.ACA.MCC.COM> Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 36 In article <1348@banach.ACA.MCC.COM>, mishra@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.