Home

Advertisement

Customize

Liam Healy

Mar. 8th, 2008

02:16 pm - Never a NaN or Inf

In very few cases is it acceptable to me that a floating-point calculation would produce NaN or Inf; it almost always means that there is an error somewhere in my program. Following the principle that it is best to detect an error as soon as possible, I would like to know immediately whenever either of these is created, by trapping the exception and signaling an error. Depending on the language and implementation, this doesn't always happen by default. Here are some different languages and compilers, and how to set to make this happen:


  • Lisp: SBCL: (sb-int:set-floating-point-modes :traps '(:invalid :divide-by-zero :overflow)) and
    CMUCL: (ext:set-floating-point-modes :traps '(:invalid :divide-by-zero :overflow)).
    Also GSLL provides #'set-floating-point-modes.
  • Fortran: for gfortran, use the compiler flag -ffpe-trap=invalid,zero,overflow.
  • C/C++: use
    #include <fenv.h>
    trapfpe () {
      feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);
    }
    

    In C, this will need to be included: void trapfpe();
    In C++, this will need to be included (also works for C):
    #ifndef _TRAPFPE_H_
    #define _TRAPFPE_H_
    
    #include <sys/cdefs.h>
    
    __BEGIN_DECLS
    void trapfpe(void);
    __END_DECLS
    
    #endif /* _TRAPFPE_H_ */
    

    and then in either, include trapfpe(); at the beginning. This should be portable to C99 compilers/libc but I've used only gcc and glibc. Also, GSL has gsl_ieee_env_setup.