When I got np.where that tries to avoid division by zero, I am still getting the error, even when p_arr - 0.5 should be always > 0.
mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)
RuntimeWarning: divide by zero encountered in true_divide
mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)
Any idea why and how to fix that? Additionally is there any way to debug it properly, so the error would show what was the exact value from p_arr?
Some tests:
x = np.where(p_arr > 0.5, p_arr, 1)
print(np.all((p_arr - 0.5 != 0))) # FALSE
print(np.all((x - 0.5 != 0))) # TRUE
pseudocode for np.where:
def np_where(chooser, true_opt, false_opt):
out = np.empty(chooser.shape, dtype = true_opt.dtype)
out[~chooser] = false_opt
return out
Importantly, true_opt is generated before calling the function. So if anything in it raises an error, the interpreter never gets to call np.where - even if np.where would never use the parts of true_opt that raise the error.
You can get rid of the divide by zero errors, but don't use np.seterr as recommended in the other answer - that will shut it off for the whole session and may cause problems with other bits of code. You can do it like this:
with np.errstate(divide='ignore'):
mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)
To find out where your error was coming from, just use:
np.where(p_arr == 0.5)
Which should give you the coordinates where you were getting the divide by zero error
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