Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

python - Numpy divide by zero encountered in true_divide on np.where()

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...