如何检查浮点变量是NaN
还是inf
。搜索isNaN
或isInf
的标准库并未显示任何内容。有blog post建议使用
proc cIsNaN(x: float): int {.importc: "isnan", header: "<math.h>".}
但是标准库中什么都没有?
答案 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
还可以测试其他属性,例如fcSubnormal
,fcNegZero
或fcNegInf
(请参阅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