Nan issues

I keep getting Nan when asking for a double value, it’s from an array of Doubles and when I view it in the debugger the array shows correct values, but when the value is then placed into another double variable I get NaN, which screws up all the math.

Xojo 2017r3 64-Bit macOS application.

How can I test for Nan?

What would cause this annoying problem?

divide by zero ?

Yes it’s possible that created the value originally.

Do you know how to test for it in code (apart from comparing both values before hand), I mean to test and see if a value is Nan?

Testing for a NAN can be done like -

dim value as double = xxx
if value<>value then
//is a NAN
end if

Be careful using the value<>value method. It can fail on 64 bit builds. This is what I use:

Function IsNaN(x As Double) as Boolean 'Test for invalid number: NaN, +inf, -inf 'Note inconsistent behaviour between 32 and 64 bit builds, #If Target32Bit return (x*0<>0) #Else Return not(x*0<>0 or x*0=0) #Endif End Function
Another option is to look at the exact bit pattern of a NaN:

Function IsNaN(x As Double) as Boolean 'Test for invalid number: NaN, +inf, -inf 'using bitwise ops static m As new MemoryBlock(8) m.DoubleValue(0) = x Return Bitwise.BitOr(m.Int64Value(0),&h800fffffffffffff)=-1 End Function

Note that these will return true not just for NaN, but also for +Inf and -Inf

I should clarify that the discrepancy is not really 32 bit vs. 64 bit. It’s actually legacy Xojo 32 bit compiler vs. LLVM compiler. Thus, the value<>value test also fails in XojoScript which uses the LLVM compiler.

I suspect that the discrepancy is a matter of semantics regarding the meaning of the “<>” comparison operator. It could be interpreted as meaning “is not equal to” or it could be interpreted as meaning “is less than or is greater than.” In most cases these are effectively the same thing. However, the first is an unordered comparison and the second is an ordered comparison. If the two compilers use different interpretations of the meaning of “<>”, that would explain why they produce different results. That would also imply that as long as an unordered comparison is used in both cases, then the results should be the same. Since the “=” comparison operator can only be interpreted as an unordered comparison, then it stands to reason that the expression "not(value=value) would work with both compilers. I just tested this, and that is indeed the case. So you could just use not(value=value) to detect NaN’s. However, that doesn’t detect +inf or -inf which you would get from division by zero.

Clear as mud?