Explain IEEE 754 NaN and infinity
Explain IEEE 754 NaN and infinity
Floating-point types can represent positive and negative infinity and NaN (not a number). Use math.IsNaN and math.IsInf to test them. NaN is unequal to every floating-point value, including itself.
package main
import ( "fmt" "math")
func main() { x := math.NaN() fmt.Println(math.IsNaN(x), x == x) fmt.Println(math.IsInf(math.Inf(-1), -1))}IsInf accepts a sign selector: zero for either sign, positive for positive infinity, negative for negative infinity. NaN and infinity are different categories.
Expected output:
true falsetrueValidate a computed value
package main
import ( "fmt" "math")
func finite(x float64) bool { return !math.IsNaN(x) && !math.IsInf(x, 0) }func main() { fmt.Println(finite(math.Sqrt(-1))) fmt.Println(finite(math.Inf(1))) fmt.Println(finite(3.5))}Sqrt of a negative real number produces NaN. Reject non-finite results when a finite value is required. A constant expression like 1/0 is instead a compilation error.
Expected output:
falsefalsetrueTry it locally
Print whether positive infinity, NaN and zero are finite.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 02: Explain IEEE 754 NaN and infinity
Check the lesson objective before moving on.
How do you detect NaN?
What does math.IsInf(x,0) test?