Inf And Nan Comparisons

lua-users home
wiki

In numerical calculations sometimes we want to compare numbers with infinites and NaN (not a number). In C (for example, in my Debian Linux) three functions are defined in <math.h>:
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 */
of clear purposes (similar functions also appear in Matlab and other languages).

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

Why not use 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
However with NaN is not possible a comparison because IEEE 754 states that (I think to remember) any comparison with NaN gives false:
math.nan = 0/0                   --> nan
x, y = 0, 0
print(x/y == math.nan)           --> false
Therefore in Lua (and directly in C) we cannot test the 'NaN' character of a numerical expression.

Actually, I think the following works. We rely on the property that NaN is the only value that doesn't equal itself. -- DavidManura
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.

-- JulioFernandez

However, these are simple to write in Lua and without the overhead of a function call, and I think they are more clear.--DavidManura
        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


RecentChanges · preferences
edit · history
Last edited September 30, 2006 1:21 am GMT (diff)