IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
6.3 IEEE-754 Not a Number (NAN) and Infinity


6.3 IEEE-754 Not a Number (NAN) and Infinity

numarray.ieeespecial has support for manipulating IEEE-754 floating point special values NaN (Not a Number), Inf (infinity), etc. The special values are denoted using lower case as follows:
>>> import numarray.ieeespecial as ieee
>>> ieee.inf
inf
>>> ieee.plus_inf
inf
>>> ieee.minus_inf
-inf
>>> ieee.nan
nan
>>> ieee.plus_zero
0.0
>>> ieee.minus_zero
-0.0
Note that the representation of IEEE special values is platform dependent so your Python might for instance say Infinity rather than inf. Below, inf is seen to arise as the result of floating point division by 0 and nan is seen to arise from 0 divided by 0:
>>> a = array([0.0, 1.0])
>>> b = a/0.0
Warning: Encountered invalid numeric result(s)  in divide
Warning: Encountered divide by zero(s)  in divide
>>> b
array([              nan,               inf])
A curious property of nan is that it does not compare to itself as equal:
>>> b == ieee.nan
array([0, 0], type=Bool)
The isnan, isinf, and isfinite functions return boolean arrays which have the value True where the corresponding predicate holds. These functions detect bit ranges and are therefore more robust than simple equality checks.
>>> ieee.isnan(b)
array([1, 0], type=Bool)
>>> ieee.isinf(b)
array([0, 1], type=Bool)
>>> ieee.isfinite(b)
array([0, 0], type=Bool)
Array based indexing provides a convenient way to replace special values:
>>> b[ieee.isnan(b)] = 999
>>> b[ieee.isinf(b)] = 5
>>> b
array([ 999.,    5.])

Here's an easy approach for compressing your data arrays to remove NaNs:

>>> x, y = arange(10.), arange(10.)
>>> x[5] = ieee.nan
>>> y[6] = ieee.nan
>>> keep = ~ieee.isnan(x) & ~ieee.isnan(y)
>>> x[keep]
array([ 0.,  1.,  2.,  3.,  4.,  7.,  8.,  9.])
>>> y[keep]
array([ 0.,  1.,  2.,  3.,  4.,  7.,  8.,  9.])

Send comments to the NumArray community.