How to check for NaN in golang
Asked Answered
S

3

34

How can I check whether a float variable is NaN or not? e.g.

math.Log(1.0) // not NaN
math.Log(-1.0)  // NaN
Sassanid answered 6/7, 2015 at 12:43 Comment(0)
F
59

Use math.IsNaN(...) for that: playground

Flashy answered 6/7, 2015 at 12:46 Comment(2)
A noteworthy addendum while we're on it: math.NaN() is not equal to itself: play.golang.org/p/H_SziEAdCvcAdagio
NaN == NaN results to false in every language as per the IEEE 754 spec which nearly all languages implement en.wikipedia.org/wiki/IEEE_754Slumlord
P
17

Use math.IsNaN:

IsNaN reports whether f is an IEEE 754 “not-a-number” value.

Pelton answered 6/7, 2015 at 12:46 Comment(0)
I
4

As mentioned in Nico's comment, because NaN is defined as f != f, that's all that math.IsNaN does. See the src here.

So, you can just check:

if f != f {
    fmt.Printf("%v is NaN", f)
}

Edited to make into a standalone answer.

In answered 29/1, 2021 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.