3

I am doing some calculations with points and the vectors between the points and it is no surprise to me that I get nan for when the points are very close together. What I am trying to do now is rid all the nan values in the array that I have stored in an array along with the good data. I am hoping to just use a bit of code like so:

   if( angle[i] == nan ) { angle[i] = 0.0 };

at least that is what I have tried and I get errors when I try that. Does any one know how to get rid of nan values and replace them with just a 0.0?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Linux Rules
  • 473
  • 3
  • 9
  • 17

2 Answers2

7

Assuming this is C then use isnan from <math.h>:

#include <math.h>

if (isnan(angle[i]))
{
    angle[i] = 0.0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • I did not try your method but I am sure it would work as well, I came across that method a few times when I was looking for a solution to this myself but was unsure how to implement it. – Linux Rules Jul 19 '12 at 21:27
  • `x!=x` is usually a faster way to check for nan than `isnan(x)`. The latter is only useful in that it avoids raising floating point exception flags, but if you don't care about/don't use floating point exception flags, `x!=x` is better. – R.. GitHub STOP HELPING ICE Jul 19 '12 at 21:28
  • isnan for c99, _isnan for visual c – BLUEPIXY Jul 20 '12 at 07:07
  • Relevant: [how do I make a portable isnan/isinf function](http://stackoverflow.com/questions/2249110/how-do-i-make-a-portable-isnan-isinf-function) – Paul R Jul 20 '12 at 07:30
5

From what I remember, in every language, NaN will compare false to everything, including itself. You can use this behavior to weed it out:

if( angle[i] != angle[i] ) { angle[i] = 0.0 };

This looks like C, C++, or Java; in all of these, this trick should work.

Wug
  • 12,956
  • 4
  • 34
  • 54