Python documentation says that FloatingPointError is raised when a float calculation fails. But what is exactly meant here by "a float calculation"?
I tried adding, multiplying and dividing with floats but never managed to raise this specific error. Instead, i got a TypeError
:
10/'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Can someone help me understand when a FloatingPointError
is raised in python?
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.
It is part of the fpectl
module. The FloatingPointError
shouldn't be raised if you don't explicitly turn it on (fpectl.turnon_sigfpe()
).
However mind the note:
The
fpectl
module is not built by default, and its usage is discouraged and may be dangerous except in the hands of experts. See also the sectionfpectl-limitations
on limitations for more details.
Update: The fpectl
module has been removed as of Python 3.7.
Even with FloatingPointErrors turned on, 10/'a'
will never raise one. It will always raise a TypeError. A FloatingPointError will only be raised for operations that reach the point of actually performing floating-point math, like 1.0/0.0
. 10/'a'
doesn't get that far.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With