Nim:如何检查一个浮点数是 nan 还是 inf?
Nim: How to check if a float is nan or inf?
如何检查浮点变量是 NaN
还是 inf
。在标准库中搜索 isNaN
或 isInf
不会显示任何内容。有一个 blog post 建议使用
proc cIsNaN(x: float): int {.importc: "isnan", header: "<math.h>".}
但是标准库中真的什么都没有吗?
标准库确实提供了对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
)。
您可以添加自己的功能
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
如何检查浮点变量是 NaN
还是 inf
。在标准库中搜索 isNaN
或 isInf
不会显示任何内容。有一个 blog post 建议使用
proc cIsNaN(x: float): int {.importc: "isnan", header: "<math.h>".}
但是标准库中真的什么都没有吗?
标准库确实提供了对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
)。
您可以添加自己的功能
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