Getting FloatingPointError instead of ZeroDivisionError when dividing by zero

Viewed 526

I'm running a very time-consuming post-processor in Python and have encountered a FloatingPointError where I was expecting a ZeroDivisionError.

My code captured the possibility of a ZeroDivisionError in a try except statement:

try: a = b / abs(c) 
except ZeroDivisionError: a = 'divZero'

However, I get the following error:

FloatingPointError: divide by zero encountered in divide

Why might I get this error?

1 Answers

This will happen if:

  • You are using numpy, and
  • You have an error state for division set to error.

Since you have stated you have taken the number from an array, it appears likely those are numpy versions. You can check the error state with numpy.geterr(). You have probably called either numpy.seterr() or numpy.errstate() somewhere in your code, or a library you are using has.

For example, you can get the FloatingPointError as follows:

In [22]: np.seterr(divide="raise")
Out[22]: {'divide': 'raise', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

In [24]: b = np.float32(1)

In [25]: c = np.float32(0)

In [26]: a = b / c
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
<ipython-input-26-809085b5049b> in <module>()
----> 1 a = b / c

FloatingPointError: divide by zero encountered in float_scalars

If b and c are numpy integers rather than floats, float_scalars will be short_scalars instead. Note that numpy objects never result in a ZeroDivisionError. If you have the error state divide='ignore' or divide='warn', the result of a / 0 will be inf, and the result of a // 0 will be 0.

Although I cannot reproduce your exact error message, it may be that this is due to different versions of numpy (I`m on 1.14.5).

Related