Shashwat Anand
Shashwat Anand

Reputation: 31

why print('NaN') shows different result from print(float('NaN'))

print('NaN') 
'NaN'

but

 print(float('NaN'))
 'nan'

why this works like this and what is the difference between "NaN" and 'nan'

Upvotes: 0

Views: 331

Answers (4)

Cole
Cole

Reputation: 1745

This is because Python's NaN (Not a Number) is represented as a float (from IEEE 754 floating-point standard).

Therefore when you enter 'NaN' it will remain a str:

>>> 'NaN'
'NaN'
>>> type('NaN')
<class 'str'>

But when you attempt to convert a str representation of a float into a float, it will respond will the corresponding float representation of that str:

>>> float('123.45')
123.45
>>> type(float('123.45'))
<class 'float'>

And since 'NaN' is, technically, an identifiable str representation of a float, it converts without error:

>>> float('NaN')
nan
>>> type(float('NaN'))
<class 'float'>

Upvotes: 2

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22304

The first instance 'NaN' is a string. It has no numerical meaning.

>>> type('NaN')
<class 'str'>

The second instance is the IEEE 754 Not A Number value, it is a float.

>>> type(float('NaN'))
<class 'float'>

The representation of float('NaN') is always nan, regardless of the letter cases used to create it.

# Those all work
float('NaN')
float('nan')
float('nAn')

Note that the nan value is also accessible through the math module, like inf which is another value that comes from the IEEE 754 standard.

from math import nan, inf

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71570

@Olivier Melançon is right 'Nan' returns an string float('NaN') returns an float

So, you can check it like below:

>>> import math
>>> x=float('NaN')
>>> math.isnan(x)
True
>>> x='NaN'
>>> math.isnan(x)
Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    math.isnan(x)
TypeError: must be real number, not str
>>> 

Upvotes: 1

DEEPAK SURANA
DEEPAK SURANA

Reputation: 461

print('NaN') is just printing the argument string as it is. For the print function, it's as same as any other string.

>>> type('NaN')
<class 'str'>

whereas, float('NaN') is actually a Not A Number, which is represented as nan.

>>> type(float('NaN'))
<class 'float'>

Upvotes: 0

Related Questions