Search code examples
cprintfinfinity

print the infinite value


In my program some computation could generate 1.#INF00 or -1.#IND00 results I want to print these results - but not as 1.#INF00 and -1.#IND00 .For example for 1.#INF00 , I want to print "infinity"

infinity_print(computation(x));//results infinity result 1.#INF00

will cause "infinity" to appear on the screen

How infinity_print could be implemented?


Solution

  • You could use isinf(y) macros in c99. Otherwise it depends on your compiler, OS, architecture -- different implementations have various drawbacks.

    Here's some of possible variants:

    #include <math.h> /* isinf */
    
    #ifndef isinf
    /* Microsoft C defines _MSC_VER */
    #ifdef _MSC_VER
    #  include <float.h>
    /* 
       from Python source: PC/pyconfig.h Py_IS_INFINITY
    */
    #  define isinf(X) (!_finite(X) && !_isnan(X))
    #else
    #  ifndef isnan
    /*
       http://www.gnu.org/software/hello/manual/autoconf/Function-Portability.html
    */
    #    define isnan(X) isnan_d(X)
    static inline int isnan_d  (double x) { return x != x; }
    #  endif /* !isnan */
    #  define isinf(X) isinf_d(X)
    static inline int isinf_d  (double x) { return !isnan (x) && isnan (x - x); }
    #endif /* _MSC_VER */
    #endif /* !isinf */
    
    #ifdef gnulib
    /*
       http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob;f=lib/isinf.c;hb=HEAD
    */
    #undef isinf
    #define isinf(X) gl_isinfd(X)
    #include <float.h>
    static inline int gl_isinfd (double x) { return x < -DBL_MAX || x > DBL_MAX; }
    #endif /* gnulib */
    

    For float, long double the implementations are similar.

    Example

    #include <stdio.h>
    
    int main() {
      double x = 1./0;
    
      printf("%g", x);
      if (isinf(x))
        puts(" infinity");
      puts("\n");
    
      return 0;
    }