I'm programming with Python 2.7.6 using numpy. I have this division between two numpy matrixes V/np.dot(W,H). Sometimes happens that the denominator has some cell values equal to 0, so i get a Runtime error. I would like to implement a safe division in a efficient way. How can i write a code that performs the Matrix division and for the elements where the denominator is equal to 0 puts 0 in the output Matrix?
Numpy actually allows you to set what you'd like to do in the case of a divide by zero error - see seterr. I believe this is a global flag, though - I'm not aware of a more localized solution - if it's an issue I suppose you can just set seterr before and after your safe division.
Though you say "matrix", I assume you really want arrays since you want element-wise division. I would just do the division inside a context manager that suppresses the div0 errors. Then I would fix up the result.
# Assume V and D are arrays of the same shape
with np.errstate(divide='ignore'):
# division errors suppressed only within this block
quot = V / D
quot[D == 0] = 0
My gut tells me this is fast because it mostly keeps data in its original shape. But I have never compared it with alternative approaches.
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