Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NAN unequal to everything except true, in PHP?

In PHP, NAN compares false to 0, "0", false, array(), array(1), NAN, null and basically every other class of variable I could discern.

But NAN == true returns true. Why does NAN == true return true?

like image 758
Jerub Avatar asked Apr 01 '11 03:04

Jerub


2 Answers

In php, $x == true is the same thing as $x? true : false. That is, comparing equal to true with == and not === means that $x will evaluate to true in a boolean context.

If NAN were to evaluate to false in a boolean context, NAN == false would evaluate to true instead.

like image 135
habnabit Avatar answered Oct 16 '22 05:10

habnabit


NAN (quite NAN or signaling NAN) is a non-zero floating point value. * That is why *

sqrt(-1.0) -> NAN

There is -NAN and +NAN although since about 80286, it is just usually recognized as NAN on test.

Check your FPU floating point instruction set if you need to.

+INF and -INF are also non-zero floating point values:

- log(0.0) -> +INF
log(0.0) -> -INF

Here is a dump of the Intel floating point stack. I'll just list the few values I was talking about: (don't forget, internally, FPU is 10 bytes):

     <exp>  <mantissa>
0.0  00 00 00 00 00 00 00 00 00 00
-INF FF FF 80 00 00 00 00 00 00 00
+INF 7F FF 80 00 00 00 00 00 00 00
-NAN FF FF C0 00 00 00 00 00 00 00
+NAN 7F FF C0 00 00 00 00 00 00 00

So as you can see, only 0.0 is ZERO!

like image 30
Ron Lentjes Avatar answered Oct 16 '22 06:10

Ron Lentjes