Nim:如何检查浮子是nan还是inf?

时间:2017-02-11 15:27:01

标签: nim

如何检查浮点变量是NaN还是inf。搜索isNaNisInf的标准库并未显示任何内容。有blog post建议使用

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

但是标准库中什么都没有?

2 个答案:

答案 0 :(得分:2)

标准库确实提供了对NaN / inf的检查,但是在classify的广义概念下,这就是为什么它很容易被遗漏。举例说明:

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

输出:

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还可以测试其他属性,例如fcSubnormalfcNegZerofcNegInf(请参阅FloatClass)。

答案 1 :(得分:0)

您可以添加自己的功能

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