81

I have a variable float slope that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.

I am trying to do an if-else for when that happens. How can I do that? if (slope == nan) doesn't seem to work.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
teepusink
  • 27,444
  • 37
  • 107
  • 147

4 Answers4

212

Two ways, which are more or less equivalent:

if (slope != slope) {
    // handle nan here
}

Or

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}

(man isnan will give you more information, or you can read all about it in the C standard)

Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2 if you're just going to end up using atan on the slope instead of doing some other computation).

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
  • 98
    If I ever came across `if (foo != foo)` in some code I would let out a very audible "WTF". `isnan` seems like a *far* more clear and readable method. – Alex Wayne Aug 12 '10 at 21:17
  • 5
    @Squeegy: to someone who is familiar with floating point, they read the same. To someone who isn't, yes, `isnan` is much more clear. – Stephen Canon Aug 12 '10 at 21:23
  • `isnan(x)` defines to `x!=x` on iOS, so you are doing the exact same thing in both examples. Just a heads up for people wondering what is the best option. – Andy Jan 27 '15 at 20:22
  • 2
    @AndrewHeinlein: not exactly. It expands to `x != x`, unless you're compiling with -ffast-math or similar, in which case it expands to a call to `__isnanf` or `__isnand` (because `x != x` won't work properly under -ffast-math). So it's generally best to use `isnan`. – Stephen Canon Jan 27 '15 at 20:26
  • 1
    But, what does `__isnanf` and `__isnand` expand to? – Andy Feb 01 '15 at 22:17
  • @AndrewHeinlein they don't expand to anything, they are function calls. – Stephen Canon Feb 02 '15 at 14:52
  • 1
    @IulianOnofrei because NaN is defined to be not equal to anything, including NaN. – Stephen Canon Sep 08 '16 at 15:42
36

Nothing is equal to NaN — including NaN itself. So check x != x.

Chuck
  • 234,037
  • 30
  • 302
  • 389
7
 if(isnan(slope)) {

     yourtextfield.text = @"";
     //so textfield value will be empty string if floatvalue is nan
}
else
{
     yourtextfield.text = [NSString stringWithFormat:@"%.1f",slope];
}

Hope this will work for you.

Aswathy Bose
  • 4,279
  • 4
  • 32
  • 44
1

In Swift, you need to do slope.isNaN to check whether it is a NaN.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Zhao
  • 904
  • 1
  • 11
  • 34