Trapping quiet NaN

前端 未结 2 959
误落风尘
误落风尘 2021-02-04 07:02

I have an application where some component occasionally inserts a qNaN in a large data stream, which then invalidates the entire processing (FFT on a vector containing a single

2条回答
  •  无人及你
    2021-02-04 07:29

    If you want to make all NaNs, overflows, and zerodivides signaling during debug, it is possible.

    For gcc:

    #include 
    
    #ifndef NDEBUG
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
    #endif
    

    For Visual Studio (not tested):

    #include 
    
    #ifndef NDEBUG
    _clearfp();
    _controlfp(_controlfp(0, 0) & ~(_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW),
               _MCW_EM);
    #endif
    

    References: Microsoft, gcc.


    These functions allow to catch either NaNs, produced by floating point operations (overflows, zerodivides, invalid operations), or sNaNs, used as input to some floating point operation. They do not allow to catch qNaNs, used as input to floating point operation. For such qNaNs, the only way to find them is to check each value individually (see Luchian Grigore's answer).

    So if the component, that inserts a qNaN is in the same program, were you want to catch it, or if this component is in separate program, but you have its source codes, just enable FP exceptions with feenableexcept()/_controlfp(). Otherwise, check every value in the incoming data stream with isnan() (C++11) or with x != x.

提交回复
热议问题