1

What is the concept of NaN in PHP? When and where is it used, and why this is useful?

What is this below function used for? And please, I need an explanation of the code below.

<?php echo is_nan(200) . "<br>"; echo is_nan(acos(1.01)); ?>
hd1
  • 33,938
  • 5
  • 80
  • 91

1 Answers1

2

NaN means "Not a Number". We basically call imaginary numbers (eg: Complex Numbers) as NaN, for eg: square root of -1 (i), acos(1.01). These numbers cannot be computed / calculated.

Reference:

nan/"not a number" is not meant to see if the data type is numeric/textual/etc..

NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.

The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part. There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.

From the documentation of is_nan() function:

bool is_nan ( float $val )

Details: Checks whether val is 'not a number', like the result of acos(1.01).

Returns TRUE if val is 'not a number', else FALSE.

So, basically this function is used for checking the validity of return values of mathematical functions and operations, and expects a float as a parameter.

Now, 200 is a valid number. So, is_nan(200) will return False.

While, acos(1.01) is trying to find arc cosine of 1.01. From Mathematics, we very well know that cosine function returns value in the range of -1 to +1. So value of 1.01 (more than 1) cannot exist. Hence, acos(1.01) cannot be determined. Thus it is not a valid number. Hence, is_nan(acos(1.01)) will return True.

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57