Testing x == y

You rarely want to perform tests such as x==y on floating-point variables, except when filtering special cases. The reason is that roundoff errors usually cause differences in mathematically equivalent expressions. Even the tiniest error can foil a test for strict equality. For example, the formula for parallel resistors used in "Arithmetic with infinities" on page 195 is often rewritten in the mathematically equivalent form

With , , and hypothetical four-digit decimal arithmetic, the first formula yields 845.3 and the second 845.2. (The actual value is 845.240479...)

As another example, consider computing given the value of f at x. You might proceed by discrete steps from x to y, but using a test for equality to terminate the process could lead to an infinite loop.

      float stepsize = (y - x) / n;
      do {
          // recompute stepsize if necessary
          x += stepsize;
          f_at_x = (/* estimate f(x) */)
      
    } until (x >= y);
It is common to run a process until convergence, that is, until successive approximations are sufficiently close. Rather than testing for equality, you might want to consider the relative difference. This function returns true if the relative difference of its arguments exceeds the given tolerance.

      bool ExcessiveRelativeError(double s, double t, double tolerance) {
          return (bool) (Abs((s - t)/t) > tolerance);
      }
The next example employs a test for such relative error. When you know you're converging to zero, a simple test of the difference might suffice (and will avoid divide-by-zero).


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker