Filtering data containing NaNs

Here is another example from the LINPACK BLAS. The function ISAMax returns the index of a vector's first element with largest magnitude. The vector, pointed to by sx, has length n. This first version, adapted from the original FORTRAN, raises the invalid flag when any element of the vector is a NaN. When the vector has no numerical elements, it returns .

      int ISAMax (int n, const float *sx) {
          int ixmax = -1; // if n <= 0, return -1
          float_t sxmax = -1.0;
       
          if (n > 0)
              for (int i = 0; i < n; i++, sx++)
                  if (Abs(*sx) > sxmax) {
                      ixmax = i;
                      sxmax = Abs(*sx);
                  }
          return ixmax;
      }
When any element of the vector is a NaN, the comparison (Abs(*sx) > sxmax) raises the invalid flag, according to the IEEE floating-point standards. That might not be what you want. A variation of the test in the inner loop uses
IsGreater, which is equivalent to > but raises no flag. (This is similar in style to the library function Max in that it unexceptionally finds the largest number.)

      if (IsGreater(Abs(*sx), sxmax)) {
          ixmax = i;
          sxmax = Abs(*sx);
      }
The versions thus far have interpreted NaNs as missing, dangerous, or otherwise uninteresting data. You might want ISAMax to return the index of the first occurrence of the biggest magnitude, or the index of the first NaN:

      for (int i = 0; i < n; i++, sx++)
          if (!IsLessEqual(Abs(*sx), sxmax) {
              ixmax = i;
              if (IsNaN(*sx)) // exit if NaN
                  break;
              sxmax = Abs(*sx);
          }
This logic is more complicated because of the need to exit prematurely on the first occurrence of a NaN and because of the use of !
IsLessEqual to effect the test "is greater than or unordered with" without raising the invalid flag.


[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