Inf And Nan Comparisons |
|
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 and 5.1) can manipulate numerical infinites without problem with some tricks. We can include a new constant in math table:
math.inf = 1/0 --> inf
math.huge
instead? At least on my system, math.huge == 1/0
. --DavidManura
After that we can use it in our calculations (even in the form -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
I propose three new functions in the math library, exact mirrors of the C ones:
math.isinf(value)
Gives 1 if value is +inf, -1 for -inf, and false otherwise (even for NaN).
The numerical values are convenient: if the sign is not important for us both are true-equivalent (although may not in a next version of Lua !?)
math.isnan(value)
Gives true if value is NaN and false otherwise.
math.finite(value)
Gives true if value is not NaN and not +/-inf and false otherwise.
As these functions are nearly a mirror of the C ones, I think it will be no difficult to integrate them in Lua. Besides, they will have small size in the code.
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