3

It looks like this is true in other languages as well (see thread on C++), but does anyone know why you can't check the result of a negative square root against the Double.NaN or Double.quietNaN properties in Swift's Double struct?

Here is some code I ran in a Playground:

sqrt(-5.0)       // (not a number)
Double.NaN       // (not a number)
Double.quietNaN  // (not a number)

Double.NaN == sqrt(-5.0)       // false
Double.quietNaN == sqrt(-5.0)  // false

It seems that the Swift playground is printing sqrt(-5.0), Double.NaN, and Double.quietNaN with the same error string, but that they have different programmatic representations. I can't figure out why this is happening. Any thoughts?

Community
  • 1
  • 1
egracer
  • 362
  • 3
  • 10
  • 1
    I googled "Swift Nan" and found this answer: http://stackoverflow.com/a/24351407/2079103 – clearlight Apr 07 '15 at 00:23
  • 2
    By convention, NaN compares false against any other value, including NaN. –  Apr 07 '15 at 00:26
  • Didn't know that NaN compares false against anything else, good to know. I didn't realize Double conforms to FloatingPointNumber... kind of strange. Thanks! – egracer Apr 07 '15 at 00:41

1 Answers1

1

You can check whether a number is NaN by check its equivalent to itself:

if aNumber != aNumber {
  println("This is NaN")
}

NaN is always not equal to itself.

Or you can use the isNaN property of a Double number:

let number: Double = 5.0
let nanNumber: Double = Double.NaN

number.isNaN  // false
nanNumber.isNaN  // true

Float numbers also have a isNaN property.

mrahmiao
  • 1,291
  • 1
  • 10
  • 22