Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does python raise a FloatingPointError?

Tags:

python

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?

like image 222
DhKo Avatar asked Dec 19 '16 13:12

DhKo


2 Answers

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.
like image 117
gerrit Avatar answered Oct 23 '22 13:10

gerrit


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 section fpectl-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.

like image 27
MSeifert Avatar answered Oct 23 '22 12:10

MSeifert