無窮大與 NaN 比較 |
|
int isinf(double value); /* gives -1 for -inf, 1 for inf, 0 otherwise */ int isnan(double value); /* gives 1 for NaN, 0 otherwise */ int finite(double value); /* gives 1 for not NaN and not inf */
Lua (5.0 和 5.1) 可以通過一些技巧,毫不費力地處理數值無窮大。我們可以在數學表中包含一個新常數
math.inf = 1/0 --> inf
math.huge
呢?至少在我的系統上,math.huge == 1/0
。⸺DavidManura
在那之後,我們可以在計算中使用它 (甚至以 -math.inf 形式)
x = 3 print(x/0 == math.inf) --> true print(math.log(0) == -math.inf) --> true
math.nan = 0/0 --> nan x, y = 0, 0 print(x/y == math.nan) --> false
local z = 0/0 -- nan print(z ~= z) --> true
我在數學函式庫中提議三個新函式,它們是 C 中函式的精確鏡像
math.isinf(value)
如果 value 為 +inf,則返回 1,如果為 -inf,則返回 -1,否則返回 false (即使是 NaN)。
數值非常方便:如果符號對我們來說並不重要,那麼兩者都是真值等價的 (儘管在 Lua 的下一個版本中可能不是!?)
math.isnan(value)
如果 value 為 NaN,則返回 true,否則返回 false。
math.finite(value)
如果 value 不是 NaN 也不是 +/-inf,則返回 true,否則返回 false。
由於這些函式幾乎是 C 中函式的鏡像,所以我認為將它們整合到 Lua 中並不會很困難。此外,它們在程式碼中的大小也會很小。
x == math.huge -- test for +inf x == -math.huge -- test for -inf -- The following assume type(x) == "number": x ~= x -- test for nan x > -math.huge and x < math.huge -- test for finite