54
votes

I am doing some simple math recessively in a python script and am getting the follow warning:

"Warning: divide by zero encountered in divide".

To provide some context, I am taking two values and trying to find the percent difference in value (a - b) / a and if its above a certain range then process it, but sometimes the value of a or b is zero.

I want to get rid of this specific warning (at a specific line) but all the information I have found so far seems to show me how to stop all warnings (which I do not want).

When I used to write shell scripts, I could do something like this

code...
more code 2 > error.txt
even more code  

In that example, I would get the warnings for the 'code' and 'even more code' command but not for the second line.

Is this possible?

2
Why not check if a or b == 0 and not do the computation?AlG
That isn't a usual Python warning, can you show the code you're running?Ned Batchelder
that should be an exception, not a warning, no? can't you catch the ZeroDivisionError?mpen
I thought of that, but the result(which is zero) is exactly what I want already. I think worst case, I will just do that, but I was curious if there was a way to suppress specific messages in python.Lostsoul
It is a warning, I'm using numpy/scipy and I think those modules are generating the error when I'm dividingLostsoul

2 Answers

14
votes

I'd avoid the division-by-zero in the first place:

if a == 0:
    # Break out early

# Otherwise the ratio makes sense

If you do want to squash that particular numpy warning on a single line, numpy provides a way:

with numpy.errstate(divide='ignore'):
    # The problematic line
111
votes

If Scipy is using the warnings module, then you can suppress specific warnings. Try this at the beginning of your program:

import warnings
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

If you want this to apply to only one section of code, then use the warnings context manager:

import warnings
with warnings.catch_warnings():
    warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
    # .. your divide-by-zero code ..