Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace division by zero numpy

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?

like image 614
Jan van der Vegt Avatar asked May 30 '16 20:05

Jan van der Vegt


People also ask

How does Numpy handle division by zero?

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.

How do you fix zero division error in Python?

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.

How do you use element wise division in Numpy?

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).

How do I divide a Numpy array by a constant?

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.


1 Answers

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)
like image 110
Chiel Avatar answered Oct 12 '22 05:10

Chiel