Why float('Nan') == float('Nan') is False

Chris Angelico rosuav at gmail.com
Thu Feb 14 11:58:03 EST 2019


On Fri, Feb 15, 2019 at 3:56 AM Joe Pfeiffer <pfeiffer at cs.nmsu.edu> wrote:
>
> ast <none at gmail.com> writes:
>
> > 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')
>
> import math
> while math.isnan(r) :
>
> will do what you're looking for.
>
> If you're using python 3.5 or higher, you can also use math.nan instead
> of float('nan').

Or even better, use None instead of nan. There's nothing in Python
says you have to (ab)use a floating-point value as a signal. Or use
"while True" and add a break if the exception isn't thrown.

ChrisA



More information about the Python-list mailing list