Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...