I have written a program to print a matrix after some computations and I am getting an output of nan
for all elements. I want to break a for
loop as soon as the matrix's first element becomes nan
to understand the problem. How can I do this? In the terminal, I have printed the matrix a
containing nan
as all elements and typed a[1][1]=="nan"
and a[{{1},{1}}]=="nan"
both of which return false
. Why are they not returning false
and what statement should I use instead?
Asked
Active
Viewed 1.6k times
6

Sibi
- 2,221
- 6
- 24
- 37
-
2`local function isNaN( v ) return type( v ) == "number" and v ~= v end` – siffiejoe Jun 10 '16 at 17:15
-
1`local function isNaN( v ) return tostring(v) == tostring(0/0) end` – Egor Skriptunoff Jun 10 '16 at 17:41
-
@EgorSkriptunoff -(0/0) results in a different string even though it is still nan thus returning false even though true should be returned. https://ideone.com/YoOljy – Rochet2 Jun 11 '16 at 20:04
-
@Rochet2 - Yes, you are correct. – Egor Skriptunoff Jun 12 '16 at 00:09
3 Answers
20
Your test fails because you are comparing a number with a string, "nan"
.
If you are sure it's a number, the easiest way is:
if a[1][1] ~= a[1][1] then
because according to IEEE 754, a nan
value is considered not equal to any value, including itself.

Yu Hao
- 119,891
- 44
- 235
- 294
8
Two solutions:
local n = 0/0 -- nan
-- first solution
if ( tostring(n) == "nan" ) then
print("is nan!!")
end
-- second solution
if (n ~= n) then
print("is nan!!")
end

rsc
- 10,348
- 5
- 39
- 36
-
3Per this question on [Is there a way to detect NaN and -NaN?](https://stackoverflow.com/a/52280708/1366033), `"nan"` is "*not portable*", presumably because that's the `tostring` output on linux while [windows uses `#IND`](https://stackoverflow.com/q/19107302/1366033). So the safer equation is to repeat the `tostring` of something we know to be NaN (i.e. `0/0`) like this: `tostring(n) == tostring(0/0)` – KyleMit Dec 16 '20 at 23:44
-5
Try this:
for x = 1, x2 do -- x2 depends on how big you matrix is.
for y = 1, y2 do -- y2 the same as x2
-- some code depending on how your program works
if a[x][y] == nan then
print( "X:" .. x .. ", Y:" .. y )
break
end
end
end
PS: (nan == nan) is true

BlackHack
- 1
- 1
- 2
-
2Your answer is incorrect. The variable "nan" is not defined in Lua, so it will evaluate to (nil). (nil == nil) is indeed true. However, (0/0 == 0/0) is false! – joshuahhh Oct 17 '17 at 00:54
-
1