Python Forum
Why is bool(float("nan")) == True?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is bool(float("nan")) == True?
#1
Why is
bool(float("nan")) == True
?
Reply
#2
bool(float_value) is True for all float values != 0.0. nan does not equal 0.0
Reply
#3
The bool class can be used to type cast a string into a bool. An empty string will return False:

empty_string = ''
bool(empty_string)
A non-empty string returns True:

non_empty_string = 'nan'
bool(non_empty_string)
The bool class can be used to type cast a float into a bool. A float of value 0.0 will return False:

bool(0.0)
Any other float returns True:

bool(0.1)
bool(float('nan'))
And the following is True:

float('nan') != 0.0
RockBlok likes this post
Reply
#4
The documentation is interesting and also telling some facts about the C99 Standard.

https://docs.python.org/3/library/math.h...n#math.nan

Quote:A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan'). Due to the requirements of the IEEE-754 standard, math.nan and float('nan') are not considered to equal to any other numeric value, including themselves. To check whether a number is a NaN, use the isnan() function to test for NaNs instead of is or ==. Example:

One solution to get a False could be:
import math


result = not math.isnan(float("nan"))
RockBlok likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(Dec-30-2023, 06:50 PM)DeaD_EyE Wrote: Due to the requirements of the IEEE-754 standard, math.nan and float('nan') are not considered to equal to any other numeric value, including themselves.
>>> float('nan') == float('nan')
False
>>> 
>>> x = float('nan')
>>> x == x
False
>>> 
That's because you can never tell where a NaN value comes from, and the IEEE-754 format allows several NaN values.
RockBlok likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020