Miscellaneous — NumPy v1.13 Manual (original) (raw)

IEEE 754 Floating Point Special Values

Special values defined in numpy: nan, inf,

NaNs can be used as a poor-man’s mask (if you don’t care what the original value was)

Note: cannot use equality to test NaNs. E.g.:

myarr = np.array([1., 0., np.nan, 3.]) np.where(myarr == np.nan) np.nan == np.nan # is always False! Use special numpy functions instead. False myarr[myarr == np.nan] = 0. # doesn't work myarr array([ 1., 0., NaN, 3.]) myarr[np.isnan(myarr)] = 0. # use this instead find myarr array([ 1., 0., 0., 3.])

Other related special value functions:

isinf(): True if value is inf isfinite(): True if not nan or inf nan_to_num(): Map nan to 0, inf to max float, -inf to min float

The following corresponds to the usual functions except that nans are excluded from the results:

nansum() nanmax() nanmin() nanargmax() nanargmin()

x = np.arange(10.) x[3] = np.nan x.sum() nan np.nansum(x) 42.0

How numpy handles numerical exceptions

The default is to 'warn' for invalid, divide, and overflowand 'ignore' for underflow. But this can be changed, and it can be set individually for different kinds of exceptions. The different behaviors are:

These behaviors can be set for all kinds of errors or specific ones:

Note that integer divide-by-zero is handled by the same machinery. These behaviors are set on a per-thread basis.

Examples

oldsettings = np.seterr(all='warn') np.zeros(5,dtype=np.float32)/0. invalid value encountered in divide j = np.seterr(under='ignore') np.array([1.e-100])**10 j = np.seterr(invalid='raise') np.sqrt(np.array([-1.])) FloatingPointError: invalid value encountered in sqrt def errorhandler(errstr, errflag): ... print("saw stupid error!") np.seterrcall(errorhandler) <function err_handler at 0x...> j = np.seterr(all='call') np.zeros(5, dtype=np.int32)/0 FloatingPointError: invalid value encountered in divide saw stupid error! j = np.seterr(**oldsettings) # restore previous ... # error-handling settings

Interfacing to C

Only a survey of the choices. Little detail on how each works.

  1. Bare metal, wrap your own C-code manually.
  1. Cython
  1. ctypes
  1. SWIG (automatic wrapper generator)
  1. scipy.weave
  1. Psyco

Interfacing to Fortran:

The clear choice to wrap Fortran code isf2py.

Pyfort is an older alternative, but not supported any longer. Fwrap is a newer project that looked promising but isn’t being developed any longer.

Interfacing to C++:

  1. Cython
  2. CXX
  3. Boost.python
  4. SWIG
  5. SIP (used mainly in PyQT)