问题
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