Floating point equality

Schauble at mit-multics.arpa Schauble at mit-multics.arpa
Thu Mar 12 16:21:43 AEST 1987


Branner at TCGOULD.TN.CORNELL.EDU writes

In many numerical programs you do not want to repeat some calculation
if some floating-point variable has not changed.  Therefore,

          double x,y;
          x = y;
          ...
          if (x==y) ...

SHOULD be available (and work correctly) even in implementations where
(x*y == y*x) fails.  And it should be no problem to implement, since
x and y are two copies of the same number in the same internal format.
(This is very different from the common mistake of expecting infinite
precision when using FP variables in loop termination criteria...)

- Moshe Braner

2--------------------

It's rare that the two numbers are just exact copies of the same
variable. Usually one goes through slightly different calculation paths.
Also, as an extreme case, I know of one compiler where
    x=y
    if(x==y)
would fail because the x=y did rounding.

None of this mentions the countless times I've seen people using equal
to end loops, mathematical types who were surprised that sin(PI) != 1.0,
annd so on.

I'll stand by my original comment. Test for equality on floating point
numbers is machine and compiler dependant. the only question is do we
tell people about this.

For your example, you should have written 
    if (fabs(x-y) < EPSILON)

    Paul
    Schauble at MIT-Multics.edu



More information about the Comp.lang.c mailing list