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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With