I'm doing a matrix by matrix pointwise division however there are some zeros in the divisor matrix. This results in a warning and in some NaNs. I want these to map to 0, which I can do like this:
edge_map = (xy/(x_norm*y_norm))
edge_map[np.isnan(edge_map)] = 0
However there are two issues with this, first of all it still gives a warning (I don't like warnings) and second of all this requires a second pass over the matrix (not sure if this is unavoidable) and efficiency is very important for this part of the code. Ideas?
Behavior on division by zero can be changed using seterr. When both x1 and x2 are of an integer type, divide will return integers and throw away the fractional part. Moreover, division by zero always yields zero in integer arithmetic.
Conclusion # The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.
divide() in Python. numpy. divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise).
Dividing a NumPy array by a constant is as easy as dividing two numbers. To divide each and every element of an array by a constant, use division arithmetic operator / . Pass array and constant as operands to the division operator as shown below. where a is input array and c is a constant.
This is probably the fastest solution, but the where
function does trigger the error as it precalculates the solutions:
import numpy as np
n = 4
xy = np.random.randint(4, size=(n,n)).astype(float)
x_norm = np.random.randint(4, size=(n,n)).astype(float)
y_norm = np.random.randint(4, size=(n,n)).astype(float)
xy_norm = x_norm*y_norm
edge_map = np.where(xy_norm == 0, xy_norm, xy/xy_norm)
print(xy)
print(xy_norm)
print(edge_map)
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