DEV Community

.
.

Posted on

Division by zero in pure python vs numpy

Today I learned that if you're trying to divide by zero and that zero is a Numpy type, the compiler will not raise the ZeroDivisionError but only RuntimeWarning and it will assign numpy.inf to the value. numpy.inf is IEEE 754 floating point representation of positive infinity, according to the docs.

Example:

import numpy as np

try:
    a = 1 / 0
except ZeroDivisionError:
    print("You can't divide by zero!") 

try:
    b = np.intc(1) / np.intc(0)
    print('Hello numpy, b is: ', b)
except ZeroDivisionError:
    print("Can you divide by zero?")

Enter fullscreen mode Exit fullscreen mode

output:

>>You can't divive by zero!
>>RuntimeWarning: divide by zero encountered in int_scalars
  num = np.intc(1) / np.intc(0)
Hello numpy, b is:  inf
Enter fullscreen mode Exit fullscreen mode

Top comments (0)