Floating point error handling#
Error handling settings are stored incontextvarsallowing different threads or async tasks to have independent configurations.For more information, seeThread Safety.
How numpy handles numerical exceptions#
The default is to'warn' forinvalid,divide, andoverflowand'ignore' forunderflow. But this can be changed, and it can beset individually for different kinds of exceptions. The different behaviorsare:
'ignore': Take no action when the exception occurs.'warn': Print aRuntimeWarning(via the Pythonwarningsmodule).'raise': Raise aFloatingPointError.'call': Call a specified function.'print': Print a warning directly tostdout.'log': Record error in a Log object.
These behaviors can be set for all kinds of errors or specific ones:
all: apply to all numeric exceptionsinvalid: when NaNs are generateddivide: divide by zero (for integers as well!)overflow: floating point overflowsunderflow: floating point underflows
Note that integer divide-by-zero is handled by the same machinery.
The error handling mode can be configurednumpy.errstatecontext manager.
Examples#
>>>withnp.errstate(all='warn'):...np.zeros(5,dtype=np.float32)/0.0<python-input-1>:2: RuntimeWarning: invalid value encountered in dividearray([nan, nan, nan, nan, nan], dtype=float32)
>>>withnp.errstate(under='ignore'):...np.array([1.e-100])**10array([0.])
>>>withnp.errstate(invalid='raise'):...np.sqrt(np.array([-1.]))...Traceback (most recent call last): File"<python-input-1>", line2, in<module>np.sqrt(np.array([-1.]))~~~~~~~^^^^^^^^^^^^^^^^^FloatingPointError:invalid value encountered in sqrt
>>>deferrorhandler(errstr,errflag):...print("saw stupid error!")>>>withnp.errstate(call=errorhandler,all='call'):...np.zeros(5,dtype=np.int32)/0saw stupid error!array([nan, nan, nan, nan, nan])
Setting and getting error handling#
| Set how floating-point errors are handled. |
| Get the current way of handling floating-point errors. |
| Set the floating-point error callback function or log object. |
Return the current callback function used on floating-point errors. | |
| Context manager for floating-point error handling. |