7

I'm fairly new to Lua. While testing I discovered #INF/#IND. However, I can't find a good reference that explains it.

What are #INF, #IND, and similar (such as negatives) and how do you generate and use them?

Nathan Goings
  • 1,145
  • 1
  • 15
  • 33
  • 1
    `1/0`, `-1/0` and `0/0` – Egor Skriptunoff Oct 01 '13 at 03:43
  • Your Lua build must be using a floating-point type for Lua's `number` type. (The default Lua build uses the C `double` type.) See [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) by David Goldberg. – Tom Blodget Oct 02 '13 at 10:45

3 Answers3

11

#INF is infinite, #IND is NaN. Give it a test:

print(1/0)
print(0/0)

Output on my Windows machine:

1.#INF
-1.#IND

As there's no standard representation for these in ANSI C, you may get different result. For instance:

inf
-nan
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 3
    `-1.#IND` is a particular NaN pattern known as `INDEFINITE`. The bit pattern for the double-precision version is `0xfff800000000000`. – njuffa Oct 01 '13 at 21:54
7

Expanding @YuHao already good answer.

Lua does little when converting a number to a string, since it heavily relies on the underlying C library implementation. In fact Lua print implementation calls Lua tostring which in turn (after a series of other calls) uses the lua_number2str macro, which is defined in terms of C sprintf. Thus in the end you see whatever representation for infinities and NaNs the C implementation uses (this may vary according to which compiler was used to compile Lua and which C runtime your application is linked to).

5

@YuHao has already answered what the OP has effectively asked: what does +/-1.#INF (+-inf) and -1.#IND (nan) mean. What I want to do here is just to add some value to the question/answer by expanding on to deal with -- to check -- them (which I just needed and learned to):

  • inf (+/-1.#INF) are the highest number(+/-) that Lua can represent, and the Language provides such value(s) for you through math.huge. So you can test if a number is +/-INF:
local function isINF(value)
  return value == math.huge or value == -math.huge
end
  • nan (-1.#IND) is something that can not be handled numerically, and the result of any operation involving it is also Not-a-number(*). Long-story-short... if a number is a NaN, comparing it against itself will (always) be False. The function below implements the simplest way for checking if a NaN:
local function isNAN(value)
  return value ~= value
end

(*): This (NaN) is formally defined some where in the IEEE754 standard (floating-point numbers).

Brandt
  • 5,058
  • 3
  • 28
  • 46