## Notes on Python cookbook 3rd (3.7): infinity and Nan

Giant ship 2020-11-17 00:24:44
notes python cookbook 3rd rd

# Infinity and NaN

## problem

You want to create or test infinite 、 Negative infinity or NaN( The digital ) Floating point number .

## solution

Python There is no special syntax for these special floating-point values , But you can use float() To create them . such as ：

``````>>> a = float('inf')
>>> b = float('-inf')
>>> c = float('nan')
>>> a
inf
>>> b
-inf
>>> c
nan
>>>
``````

To test the existence of these values , Use math.isinf() and math.isnan() function . such as ：

``````>>> math.isinf(a)
True
>>> math.isnan(c)
True
>>>
``````

## Discuss

Want to know more about these special floating point values , You can refer to IEEE 754 standard . However , There are also some things you need to pay special attention to , Especially when it comes to comparisons and operators .

Infinity propagates as it performs mathematical calculations , such as ：

``````>>> a = float('inf')
>>> a + 45
inf
>>> a * 10
inf
>>> 10 / a
0.0
>>>
``````

But some operations are undefined and return a NaN result . such as ：

``````>>> a = float('inf')
>>> a/a
nan
>>> b = float('-inf')
>>> a + b
nan
>>>
``````

NaN Values are propagated through all operations , There is no exception . such as ：

``````>>> c = float('nan')
>>> c + 23
nan
>>> c / 2
nan
>>> c * 2
nan
>>> math.sqrt(c)
nan
>>>
``````

NaN The comparison between them always returns False. such as ：

``````>>> c = float('nan')
>>> d = float('nan')
>>> c == d
False
>>> c is d
False
>>>
``````

For this reason , Test one NaN Worth The only safe way Is the use of math.isnan() , It's just like the one shown above .

Sometimes programmers want to change Python Default behavior , In return to infinity or NaN An exception is thrown in the resulting operation . fpectl Modules can be used to change this behavior , But it's in the standard Python It's not being built Enable , It's platform related , And it's for expert programmers .