2

I have a piece of Javascript code and i am trying to convert it into C code. I have a problem to convert following line to C:

var q = (!isNaN(dLat/dPhi)) ? dLat/dPhi : Math.cos(lat1);

Can you tell me equivalent of isNan in C? Thanks.

Azeem
  • 2,904
  • 18
  • 54
  • 89
  • are you trying to determine if is not null? if so check this out: http://stackoverflow.com/questions/872323/method-call-if-not-null-in-c-sharp – Alex Feb 11 '12 at 12:17
  • I am trying to determine that if its not a number(isNan).Can you please tell me how to use isnan function in C? – Azeem Feb 11 '12 at 12:20

4 Answers4

6

C has an isnan macro in math.h (this is a C99 addition).

The macro return an non-zero int only if the argument is a NaN value.

ouah
  • 142,963
  • 15
  • 272
  • 331
3

Don't feel foolish, but it's:

isnan(x)

You can also use fpclassify and check if the return result is FP_NAN.

isnan was first introduced in 3BSD but didn't go into the cross-platform spec until C99. fpclasify turned up in C99. They're in math.h.

Microsoft supply _isnan in MSVC, in float.h.

Tommy
  • 99,986
  • 12
  • 185
  • 204
3

On first sight, it looks like the original author just wanted to check for dPhi being 0, so you might want to substitute that. However, if you want to translate the code verbatim, simply use the isnan macro from math.h, like this:

#include <math.h>

double q = (!isnan(dLat/dPhi)) ? dLat/dPhi : cos(lat1);
Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
phihag
  • 278,196
  • 72
  • 453
  • 469
  • This line gives following error: error C2143: syntax error : missing ';' before 'type' I am using Visual C++ 6.0 – Azeem Feb 11 '12 at 12:26
  • That sounds like there is a typo in one of the preceding lines. Try reproducing the problem with as few lines possible (say, 10, including the main function). If that doesn't solve it for you in the process, please ask a new stackoverflow question and include the full code. – phihag Feb 11 '12 at 12:30
  • I changed the code as you suggested on first sight: if (dPhi == 0) q = cos(lat1R); else q = dLat/dPhi; thanks. – Azeem Feb 11 '12 at 12:33
  • Substituting `if (dPhi == 0)` makes a difference if it's possible that either `dLat` or `dPhi` is a NaN. In the original Javascript, `cos(lat1)` is returned when either input is a NaN. – Steve Jessop Feb 11 '12 at 13:50
  • 1
    The check (dPhi == 0) is not the same! The expression dLat/dPhi becomes only NaN if dPhi == dLat == 0 or dPhi == dLat == infinite or as @SteveJessop mentioned one or both are NaN. For example 5/0 is infinite and not NaN. – quinmars Feb 11 '12 at 17:33
3

Assuming your C implementation is modern (i.e. anything but MSVC) you should have isnan available in math.h. Otherwise, if (x!=x) is a perfectly good way to check for NAN if you don't care about it modifying the floating point exception flags (which almost nobody uses or cares about).

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711