Yes, I pointed that out in my earlier post; it returns true for NaN, inf and -inf, which is what I find most useful for my needs. If you need to distinguish between these three results, then Christian’s suggestion of using the x<>x test will return true only for NaN’s.
I also need to post a warning about using these functions. Michel was correct about reliability. I was testing these again today, and discovered that both my function And Christian’s function fail in 64 bit builds. I came up with a workaround for my function, but haven’t yet attempted a workaround for Christian’s.
Public Function IsNaN1(x As Double) as Boolean
#If Target32Bit
return (x*0<>0)
#Else
Return not(x*0<>0 or x*0=0)
#Endif
End Function
But please note that this has only been tested on Macintosh builds. So, if you wish to use it, then it should be tested on whichever hardware it’s to be deployed on.
Because of this inconsistency, I decided to look at other ways of testing for NaN’s. The most direct is to look at the bit pattern of the result of the mathematical operation. So, I came up with this alternative function:
Public Function IsNaN2(x As Double) as Boolean
'Test for invalid number: NaN, +inf, -inf
static m As new MemoryBlock(8)
m.DoubleValue(0) = x
Return Bitwise.BitOr(m.Int64Value(0),&h800fffffffffffff)=-1
End Function
This can easily be modified to distinguish between NaN, inf and -inf.
For comparison purposes, I also put together a string based function:
Public Function IsNaN3(x As Double) as Boolean
return InStr(str(x),"N")>0
End Function
Speed testing these three functions by running each one 10 million times, I get the following results:
Function Time (32 bit) Time (64 bit)
-------- ------------- -------------
IsNan1 2.773251 sec. 0.5279456 sec.
IsNan2 2.395691 sec. 1.862914 sec.
IsNan3 12.01183 sec. 9.931013 sec.