How to check for Nan ??

kirkir
edited October 2015 in Questions about Code
HI ,

I am struck with this small problem.Would some one help me to find way out ??

Am performing small calculation where I am not sure whether it will return the valid result or not .
For some iteration it returns the NaN (Not a Number). But what i want is to skip such iteration.
ie. if my result NaN for the iteration 5 then I would like to skip that iteration and move to the next .

here is sample.
float result;
for(int i =0; to say some 100)
 { 
    result = some operation;
    if (result==NaN)
    { 
      result= 0;
      }
  sum = sum + result;

}
Tagged:

Answers

  • Answer ✓

    Float.isNaN(result)

  • edited October 2015 Answer ✓

    Fastest way is if (result != result) continue;. ~O)
    It's also more cross-mode compatible w/ "JS Mode" than Float.isNaN(). L-)

  • @benja : thank u @GoToLoop : Thank U

  • edited October 2015

    An alt. version which relies on the ternary conditional operator ?:: :D
    https://Processing.org/reference/conditional.html

    // forum.Processing.org/two/discussion/13000/how-to-check-for-nan
    // GoToLoop (2015-Oct-14)
    
    final float[] VALS = {
      PI, TAU, Float.NaN, sqrt(3.0), EPSILON
    };
    
    float r = 0;
    
    for (float f : VALS)  r += f == f? f : 0.0;
    //for (float f : VALS)  r += f;
    
    println(r); // 11.156929
    exit();
    

    P.S.: Uncomment line for (float f : VALS) r += f; in order to see the NaN result. >-)

Sign In or Register to comment.