Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!quanta.eng.ohio-state.edu!baloo.eng.ohio-state.edu!rob From: rob@baloo.eng.ohio-state.edu (Rob Carriere) Newsgroups: comp.lang.c Subject: Re: Floating point non-exactness Message-ID: <5467@quanta.eng.ohio-state.edu> Date: 31 Jul 90 18:31:40 GMT References: <622@.tetrauk.UUCP> Sender: news@quanta.eng.ohio-state.edu Reply-To: rob@baloo.eng.ohio-state.edu (Rob Carriere) Organization: The Ohio State University Dept of Electrical Engineering Lines: 50 Nntp-Posting-Host: baloo In article <622@.tetrauk.UUCP> rick@tetrauk.UUCP (Rick Jones) writes: > >(This is nothing to do with unsigned integers :-) Are you sure? It's a floating subject after all... >The problem is well-known - not every rational decimal number has an exact >representation in binary floating-point form. This leads to anomalies such >as: [example: computattion != math result] > >Is there a general solution to this problem without continuously rounding >everything? I believe it's possible by applying a "maximum reliable precision" >concept to FP numbers. For IEEE 64-bit numbers this seems to be 1 in 10^16, or >15 significant digits. Using this, a function "fpcmp" can be written which >takes 2 arguments: [and finds whether they are within float epsilon of each other] Hm.. Are you sure this is what you want? In your normal everyday floating point problem, the inaccuracies resulting from real-world problems tend to greatly exceed those from the computer's FP system. If I measure the `resistance' of your average resistor, I had better not peek much further than 3 to 4 decimal digits of precision, or I will see that the resistance of this thing isn't constant after all --> the model (Ohm's Law in this case) doesn't match reality. Further, I doubt my multimeter is going to give me more tham 2 digits anyway (and I wouldn't stake anything on the exactness of the 2nd digit unless the thing's been calibrated recently) --> measurement error. OK, so this resistor is 3.1 kOhm. I tell my nifty-dandy program this and it comes back with the result that the eggs will take 182.14142314159 s to finish. How many digits of that answer do you trust? And we haven't even touched the numerical conditioning of that program yet. :-) In other words, usually what you want is something like int fcmp( double a, double b, double eps ) { if ( fabs( a-b ) < eps ) return 0; if ( a > b ) return 1; return -1; } where eps will be more than large enough that you don't have to worry about the FP system messing up the comparison. (Optimization of the above code is left as an excercise for th reader. After all, I already did the easy part :-) SR ---