Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!ncar!ico!rcd From: rcd@ico.isc.com (Dick Dunn) Newsgroups: comp.unix.wizards Subject: Re: Floating Point Expectations Summary: a simpler position on the whole matter Message-ID: <1990May31.001618.24274@ico.isc.com> Date: 31 May 90 00:16:18 GMT References: <411@yonder.UUCP> Organization: Interactive Systems Corporation, Boulder, CO Lines: 42 michael@yonder.UUCP (Michael E. Haws) writes: > Is it reasonable to expect that the following code should > work the same on all platforms, and produce "good" results? > > if ((45.0 / 100.0) == .45) > printf("good\n"); > else > printf("bad\n"); Leaving aside for a moment all the nasty things that can go wrong with floating-point equality, you might note a couple of things here and ask some simpler questions: Note that the given expression contains a division of a couple of integral values in float notation. On almost all architectures, these should be represented exactly. The question could be interpreted as whether the machine is able to do an accurate division for these particular operands. Another way to look at it is to think about the process of forming the float constant ".45". This is often done by taking the string of digits (45) and scaling by an appropriate power of ten, which is remarkably close in semantics to 45.0/100.0. Yet a third viewpoint is that the entire expression is constant; a good compiler ought to evaluate it carefully. The likelihood that it will come up true, while admittedly not a certainty, ought to be higher than or equal to the likelihood that it comes up true if calculated at run time. For the particular example given, it's more surprising to get the answer "false" than for just some random example of a floating-point equality test. _ _ _ _ _ Also, in passing I'll note that the business of equality comparison with an error tolerance can be just as risky as exact equality. Suppose we define this near equality as a function (or macro or whatever) "almostequal(a,b)". The nasty is that this function is not transitive--you can have three values such that "almostequal(a,b)" and "almostequal(b,c)" are true, but "almostequal(a,c)" is false. This can trap an unwary programmer. -- Dick Dunn rcd@ico.isc.com uucp: {ncar,nbires}!ico!rcd (303)449-2870 ...Simpler is better.