Other people have replied well enough with better ways to do this but I am 
stuck on WHY this was seen as a way to do this at all.

The code was:

r = float('Nan')

while r==float('Nan'):
     inp = input("Enter a number\n")
     try:
        r = float(inp)
     except ValueError:
        r = float('Nan')

But with a single exception, what the user types in to the input statement is 
either a valid number OR it throws an exception. The exception is a string like 
"nan" which does indeed return something unusual:

>>> a = float('nan')
>>> a
Nan

With that exception, any sentinel is legitimate for such use such as a Boolean 
valid = False that you reset to true if float(inp) is working.

So what if the user types in some variant of "nan" perhaps preceded or followed 
by whitespace or more?

I experimented a bit:

>>> float("nan ")
nan
>>> float("  nan")
Nan
>>> float("  nAn")
nan
>>> float("nan ny")
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    float("nan ny")
ValueError: could not convert string to float: 'nan ny'

It seems the algorithm strips whitespace on both sides and converts the text to 
upper or lower and is happy if what is left is three characters corresponding 
to n a and n.

So if you want a normal number, you have choices. One is to check the string 
explicitly before trying to float it.

if text.strip().lower() == 'nan' : ...

Another is to float it unquestioned and if exception is thrown, check the 
proper way if it is a NaN as in:

math.isnan(x)

As noted earlier, and avoiding another mathematical exploration not needed 
further in this forum, some things in python are best not to be touched 
directly but with specially created access functions that can handle them well.
 


-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon....@python.org> On 
Behalf Of ast
Sent: Thursday, February 14, 2019 2:00 AM
To: python-list@python.org
Subject: Re: Why float('Nan') == float('Nan') is False

Le 13/02/2019 à 14:21, ast a écrit :
> Hello
> 
>  >>> float('Nan') == float('Nan')
> False
> 
> Why ?
> 
> Regards
> 

Thank you for answers.

If you wonder how I was trapped with it, here is the failing program.


r = float('Nan')

while r==float('Nan'):
     inp = input("Enter a number\n")
     try:
        r = float(inp)
     except ValueError:
        r = float('Nan')
--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to