You can also trigger a FloatingPointError
within numpy
, by setting the appropriate numpy.seterr
(or numpy.errstate
context manager) flag. For an example taken from the documentation:
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
... np.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
Interestingly, it also raises FloatingPointError
when all operands are integers:
>>> old_settings = np.seterr(all='warn', over='raise')
>>> np.int16(32000) * np.int16(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in short_scalars
The documentation notes the conditions under which the FloatingPointError
will be raised:
The floating-point exceptions are defined in the IEEE 754 standard [1]:
- Division by zero: infinite result obtained from finite numbers.
- Overflow: result too large to be expressed.
- Underflow: result so close to zero that some precision was lost.
- Invalid operation: result is not an expressible number, typically indicates that a NaN was produced.
1.0/0.0
for example will raise an exception (divide by zero)! – sascha Dec 19 '16 at 13:42ZeroDivisionError
error though. – Ma0 Dec 19 '16 at 13:43fpectl.turnon_sigfpe
to intercept floating point arithmetic "Division by Zero, Overflow, or Invalid Operation" are (or may) be turned intoFloatingPointError
. – MSeifert Dec 19 '16 at 13:57