Liam Healy (lhealy) wrote,
Liam Healy
lhealy

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.
Tags: c, floating point, fortran, lisp
Subscribe
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 13 comments