Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua check if a number/value is nan

Tags:

nan

lua

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?

like image 465
Sibi Avatar asked Jun 10 '16 17:06

Sibi


People also ask

How do you know if a number is equal to NaN?

isNaN() method to check if a number is NaN, e.g. if (Number. isNaN(num)) {} . The Number. isNaN() method will return true if the provided value is NaN and has a type of number .

How do you check if a value is a number in Lua?

But if you need to know whether Lua considers it an actual number or not, rather than a string, use 'number' == type(foo) in your test conditions.

What does NaN mean in Lua?

wiki. In numerical calculations sometimes we want to compare numbers with infinites and NaN (not a number).

How do you check if a value is a string Lua?

To check wether a value is a string use type(value) == "string" . To check wether a value can be convertet do a number use tonumber(value) . It will either return a number or nil.


1 Answers

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.

like image 104
Yu Hao Avatar answered Oct 17 '22 02:10

Yu Hao