有没有办法检测 NaN 和 -NaN? [英] Is there a way to detect NaN and -NaN?
问题描述
我想将 lua 数字保存为字符串并正确处理 NaN
大小写.
I want to save lua number to string and handle NaN
case correctly.
检测任何 NaN 很容易,x ~= x
.
Detecting any NaN is easy, x ~= x
.
但是,我发现只有一种检测方法是 NaN
或 -NaN
是使用 tostring(x) == 'nan'代码>.有没有更好的方法?
However, only one way which I've found to detect is it NaN
or -NaN
is to use tostring(x) == 'nan'
. Is there a better way to do it?
推荐答案
存在两个以上的 NaN(实际上,根据 IEEE-754,有 2^52-1
个 NaN).
它们的 tostring
表示依赖于平台.
这是如何获得三个不同的 NaN 的示例(我使用的是用 Visual Studio 构建的 Lua 5.3):
There are more than two NaNs exist (actually, there are 2^52-1
NaNs according to IEEE-754).
Their tostring
-ed representations are platform-dependent.
This is an example how to get three different NaNs (I'm using Lua 5.3 built with Visual Studio):
n = string.unpack(">d", string.pack(">d", 0/0):sub(1, -2).."@")
print(0/0, -(0/0), n) --> -1.#IND 1.#QNAN -1.#QNAN
因此,不区分 NaN 的不同变体会更正确.
So, it would be more correct to not distinguish between different variants of NaN.
这篇关于有没有办法检测 NaN 和 -NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!