how do I make a portable isnan/isinf function

前端 未结 11 1462
遇见更好的自我
遇见更好的自我 2020-11-29 06:02

I\'ve been using isinf, isnan functions on Linux platforms which worked perfectly. But this didn\'t work on OS-X, so I decided to use std::is

相关标签:
11条回答
  • 2020-11-29 06:28

    This works under Visual Studio 2008:

    #include <math.h>
    #define isnan(x) _isnan(x)
    #define isinf(x) (!_finite(x))
    #define fpu_error(x) (isinf(x) || isnan(x))
    

    For safety, I recommend using fpu_error(). I believe some numbers are picked up with isnan(), and some with isinf(), and you need both to be safe.

    Here is some test code:

    double zero=0;
    double infinite=1/zero;
    double proper_number=4;
    printf("isinf(infinite)=%d.\n",isinf(infinite));
    printf("isinf(proper_number)=%d.\n",isinf(proper_number));
    printf("isnan(infinite)=%d.\n",isnan(infinite));
    printf("isnan(proper_number)=%d.\n",isnan(proper_number));
    
    double num=-4;
    double neg_square_root=sqrt(num);
    printf("isinf(neg_square_root)=%d.\n",isinf(neg_square_root));
    printf("isinf(proper_number)=%d.\n",isinf(proper_number));
    printf("isnan(neg_square_root)=%d.\n",isnan(neg_square_root));
    printf("isnan(proper_number)=%d.\n",isnan(proper_number));
    

    Here is the output:

    isinf(infinite)=1.
    isinf(proper_number)=0.
    isnan(infinite)=0.
    isnan(proper_number)=0.
    isinf(neg_square_root)=1.
    isinf(proper_number)=0.
    isnan(neg_square_root)=1.
    isnan(proper_number)=0.
    
    0 讨论(0)
  • 2020-11-29 06:29

    The following article has some interesting tricks for isnan and isinf: http://jacksondunstan.com/articles/983

    0 讨论(0)
  • 2020-11-29 06:31

    You could also use boost for this task:

    #include <boost/math/special_functions/fpclassify.hpp> // isnan
    
    if( boost::math::isnan( ... ) .... )
    
    0 讨论(0)
  • 2020-11-29 06:35

    As brubelsabs said Boost offers this feature but, as reported here, instead of using

    if (boost::math::isnan(number))
    

    This should be used:

    if ((boost::math::isnan)(number))
    
    0 讨论(0)
  • 2020-11-29 06:35

    No-one seems to have mentioned the C99 function fpclassify which returns:

    One of FP_INFINITE, FP_NAN, FP_NORMAL, FP_SUBNORMAL, FP_ZERO or implementation-defined type, specifying the category of arg.

    This works with visual studio, but I don't know about OS-X.

    0 讨论(0)
提交回复
热议问题