Infinity and Nan Problems
You want to create or test floating-point numbers with positive infinity, negative infinity, or Nan (not a number).
Solution Solutions
Python does not have a special syntax to represent these special floating-point values, but it can be used float()
to create them. Like what:
>>> a = float ( Span class= "S1" > ' inf ' ) >>> b = float ( '-inf ' ) >>> span class= "n" >c = float ( ' nan ' ) >>> ainf>>> b-inf>>> cnan>>>
In order to test the existence of these values, use math.isinf()
and math.isnan()
functions. Like what:
Math. Isinf(a)Truemath. isNaN(c)True>>>
Discuss
For more information about these special floating-point values, you can refer to the IEEE 754 specification. However, there are some places that you need to pay special attention to, especially when it relates to comparisons and operators.
Infinite numbers are propagated when performing mathematical calculations, such as:
Float(' inf ')gb inf0.0>>>
However, some operations are undefined and return a nan result. Like what:
Float(' inf ')a/ananfloat('-inf ')bnan>> >
The Nan value propagates across all operations without generating an exception. Like what:
Float(' nan ')is2 nan2 nanmath. sqrt(c)nan>>>
A special place for Nan values when a comparison operation between them always returns false. Like what:
Float(' nan ')float(' nan ')DfalseDfalse>>>
For this reason, testing a nan is worth the only safe way to use it math.isnan()
, as demonstrated above.
Sometimes programmers want to change the python default behavior and throw an exception in an operation that returns an infinity or Nan result. The fpectl
module can be used to change this behavior, but it is not enabled in standard Python builds, it is platform-dependent, and is targeted at expert programmers. You can refer to the online Python documentation for more details.
Python Digital Series-Infinity and Nan