6

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?

Sibi
  • 2,221
  • 6
  • 24
  • 37

3 Answers3

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
  • 3
    Per 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