Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact value of NaN in matlab?

Tags:

double

nan

matlab

Need to pass some data back and forth bewteen matlab and some DLL functions, one thing stand out there is that we dont know the exact numeric value of NaN in matlab, so there will be some unnecessary data processing to take these values into account.

Do anyone know the exact values or at least the ranges of values for NaN in matlab?

I am most interested in knowing the following two primative types:

(1) NaN for float (32);

(2) NaN for double (64).

like image 354
user0002128 Avatar asked Dec 27 '22 13:12

user0002128


2 Answers

According to Mathwork's documentation, NaN returns the IEEE arithmetic representation for Not-a-Number. NaN is always in floating point representation (float or double) - I don't believe there is an integer NaN.

In IEEE 754, NaN's are represented as floating point numbers with all the exponent bits set to 1 and the fractional part any non-zero value (so there are actually many ways of representing a general NaN). See "Special Values" here.

The most reliable way to test for NaN by hand is not to look for a specific value but to test that all the exponent bits are set and the fractional part is non-zero.

like image 146
Brian L Avatar answered Jan 05 '23 23:01

Brian L


You can examine the bit pattern of the specific NaN MATLAB uses by using format hex.

>> format hex
>> NaN
ans =
   fff8000000000000
>> single(NaN)
ans =
   ffc00000

If you really want to, you can build other NaNs using typecast, like so:

>> format long
>> otherNan = typecast( 1 + typecast( single(NaN), 'int32' ), 'single' )
otherNan =
   NaN
>> isnan(otherNan)
ans =
     1
>> format hex
>> otherNan
otherNan =
   ffc00001
like image 21
Edric Avatar answered Jan 06 '23 00:01

Edric