[comp.lang.c] Floating Point Comparisons

lomow@calgary.UUCP (03/20/87)

While it is clear that comparing floating point numbers using the ==
  relation is dangerous, are there similar problems with using the
  other relational operators such as <, <=, >, >=    ?

Greg Lomow

Usenet:    ....![ubc-vision,ihnp4]!alberta!calgary!lomow

john@viper.UUCP (03/23/87)

  It strikes me, that while calculations in floating point can be done
in extended precision (more significant bits then are stored), that when 
a comparison is done, it -must- be for the number of significant digits 
that would be stored if I were to transfer the result of that calculation
to a non-register variable.  The operations in question are "logical" tests,
and should not in any way be considered absolute algebraic tests...!

  All logical comparisons need to make use of an operation akin to casting
which will "cast" the internal representation into a normalized, limited 
precision, form which can be safely checked against.  This only needs to
be done to a value which does not come directly from an auto or static
variable. (the result of a calculation or an extended precision register)
If register FP variables have exactly the same number of significant digits
as an non-register variables -and- is already normalized, then this "cast"
needs to be done only on FP values which are not lvalues.

  Yes, this is a nusance for the implementor, but there is no other way 
for a comparison (of any form: == >= <= etc..) to be safely considered
"logical" across any range of tests and consistant across multiple
implementations on differnt machines.  There are many things in the
ANSI standard that will be a nusance to implementors and programmers
alike in a few situations...  This is a standard..  If we're going to
have anything akin to a rational standard and include FP calculations
in that standard, this problem MUST be delt with.  We can no longer
continue to leave things like this in the category of "implementation
dependant" problems....

--- 
John Stanley (john@viper.UUCP)
Software Consultant - DynaSoft Systems
UUCP: ...{amdahl,ihnp4,rutgers}!{meccts,dayton}!viper!john

franka@mmintl.UUCP (04/02/87)

In article <842@vaxb.calgary.UUCP> lomow@calgary.UUCP writes:
>While it is clear that comparing floating point numbers using the ==
>  relation is dangerous, are there similar problems with using the
>  other relational operators such as <, <=, >, >=    ?

Only in cases involving near-equality.  For example, don't write:

double a;

for (a = 0.0; a < 1.0; a += 0.1)
	...

because you don't know what will happen the 11th time through.  A good
general rule is: don't make comparisons between floats where you care
which result is returned when the numbers are very close.

Frank Adams                           ihnp4!philabs!pwa-b!mmintl!franka
Ashton-Tate          52 Oakland Ave North         E. Hartford, CT 06108