Search code examples
doubleinfinity

Cant rewrite variable after assigned as infinity Ansi C


I have double field ypos[] and in some cases instead of double is written into field -1.#INF00. I need to rewrite this values with 0.0, but i cant simply assign zero value, application falls everytime. Is there a way, how to solve this problem?


Solution

  • Please see http://codepad.org/KKYLhbkh for a simple example of how things "should work". Since you have not provided the code that doesn't work, we're guessing here.

    #include <stdio.h>
    #define INFINITY (1.0 / 0.0)
    
    int main(void) {
      double a[5] = {INFINITY, 1, 2, INFINITY, 4};
      int ii;
      for(ii = 0; ii < 5; ii++) {
        printf("before: a[%d] is %lf\n", ii, a[ii]);
        if(isinf(a[ii])) a[ii] = 0.0;
        printf("after:  a[%d] is %lf\n", ii, a[ii]);
      }
      return 0;
    } 
    

    As was pointed out in @doynax 's comment, you might want to disable floating point exceptions to stop them from causing your program to keel over.

    edit if your problem is caused by having taken a logarithm from a number outside of log's domain (i.e. log(x) with x<=0 ), the following code might help:

    #include <stdio.h>
    #include <signal.h>
    #include <math.h>
    
    #define INFINITY (1.0 / 0.0)
    
    int main(void) {
      double a[5] = {INFINITY, 1, 2, INFINITY, 4};
      int ii;
      signal(SIGFPE, SIG_IGN);
      a[2] = log(-1.0);
      for(ii = 0; ii < 5; ii++) {
        printf("before: a[%d] is %lf\n", ii, a[ii]);
        if(isinf(a[ii]) || isnan(a[ii])) a[ii] = 0.0;
        printf("after:  a[%d] is %lf\n", ii, a[ii]);
      }
      return 0;
    } 
    

    You get a different value for log(0.0) (namely -Inf) and for log(-1.0) (namely nan). The above code shows how to deal with either of these.