4

How can I check if a float variable is NaN or inf. Searching the standard library for isNaN or isInf does not reveal anything. There is a blog post suggesting to use

proc cIsNaN(x: float): int {.importc: "isnan", header: "<math.h>".}

but is there really nothing in the standard library?

bluenote10
  • 23,414
  • 14
  • 122
  • 178

2 Answers2

5

The standard library does provide checking for NaN/inf, but under the generalized concept of classify, which is why it is easy to miss. To illustrate:

import math

# Inf and NaN literals are defined in system.nim as
# Inf* {.magic: "Inf".} = 1.0 / 0.0
# NaN* {.magic: "NaN".} = 0.0 / 0.0

let floatsToTest = [0.0, Inf, NaN]
for x in floatsToTest:
  echo x, " is NaN ", x.classify == fcNaN
  echo x, " is inf ", x.classify == fcInf

Output:

0.0 is NaN false
0.0 is inf false
inf is NaN false
inf is inf true
nan is NaN true
nan is inf false

classify can also test for other properties like fcSubnormal, fcNegZero, or fcNegInf (see FloatClass).

bluenote10
  • 23,414
  • 14
  • 122
  • 178
-1

You can add your own function

import std/math

func is_number*(n: float): bool =
  let ntype = n.classify
  ntype == fc_normal or ntype == fc_zero or ntype == fc_neg_zero
Alex Craft
  • 13,598
  • 11
  • 69
  • 133