Lua check if a number/value is nan

一个人想着一个人 提交于 2019-12-10 23:39:02

问题


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?


回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/37753694/lua-check-if-a-number-value-is-nan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!