Infinity and NaN
You want to create or test infinite 、 Negative infinity or NaN( The digital ) Floating point number .
Python There is no special syntax for these special floating-point values , But you can use float() To create them . such as ：
'inf') > b = float('-inf') > c = float('nan') > a inf > b -inf > c nan >> a = float(
To test the existence of these values , Use math.isinf() and math.isnan() function . such as ：
> math.isinf(a) True > math.isnan(c) True >
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 ：
'inf') > a + 45 inf > a * 10 inf > 10 / a 0.0 >> a = float(
But some operations are undefined and return a NaN result . such as ：
'inf') > a/a nan > b = float('-inf') > a + b nan >> a = float(
NaN Values are propagated through all operations , There is no exception . such as ：
'nan') > c + 23 nan > c / 2 nan > c * 2 nan > math.sqrt(c) nan >> c = float(
NaN The comparison between them always returns False. such as ：
'nan') > d = float('nan') > c == d False > c is d False >> c = float(
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 .