Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Negative Square Root [duplicate]

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?

like image 974
egracer Avatar asked Aug 05 '26 08:08

egracer


1 Answers

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.

like image 76
mrahmiao Avatar answered Aug 07 '26 21:08

mrahmiao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!