How to check numeric overflow without warning in Python?

I have an expression that overflows for specific parameter values. In this case, I got what I should use the asymptotic result, using a pen and paper, and when I have such a case, I just replace it with my analytical expression.

At the moment, my code is doing something like this:

values = ExpressionThatOverFlows() # Check the ones that overflow indOverFlow = isnan(values) # Set them to the values I derived by pen and paper values[indOverFlow] = derivedValues 

My problem is that I / O explodes with "warnings." I know that itโ€™s good that he is warning me, but I obviously took care of this, so I want to silence them. Please note that I do not want to silence all types of overflow warnings, only those that are here. I thought something like this would work, but it is not:

 try: values = ExpressionThatOverFlows() except Warning: pass # and the rest of the code as it is 

I checked, but it just seems to me how to silence these warnings for the entire session or forever, but this is how I pointed out not what I want.

Thank you for your help, very grateful.

EDIT: Here comes a much smaller code that generates the problem that I have:

 from scipy import log1p, exp from numpy import array, isnan a = array([0.2222, 500.3, 0.3, 700.8, 0.111]) values = log1p(-exp(-exp(10**a - 9**a))) print values # Note the nan's indOverflow = isnan(values) values[indOverflow] = 0 

Notice how I fix the problem โ€œmanuallyโ€ at the end, but what happens in I / O:

 Warning: overflow encountered in power Warning: overflow encountered in power Warning: invalid value encountered in subtract 

I do such calculations in a loop, so I want to disable these messages (since they are already fixed and, in addition, they take a lot of time to print)

+4
source share
3 answers

You can disable numpy.seterr(over='ignore') overflow numpy.seterr(over='ignore') , see http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

+5
source

Assuming warnings use the Python warning system, you can use the catch_warnings() and simplefilter() functions from the warnings module, as shown in the documentation .

If warnings do not use this system, it is more complicated.

+2
source

The best approach is to manually examine your expression and find out which range of input parameters can be precisely processed by your explicit code. It is possible that a significant loss of accuracy occurs much earlier than a numerical overflow.

Then you should have an explicit if statement for your input variables and use your asymptotic expression for all values โ€‹โ€‹where the numerical error is known to be too high. You may need to increase the number of members in your asymptotic extension, for example. making a Taylor series about infinity. To avoid getting bored with this manually, you may find that maxima is quite useful.

0
source

Source: https://habr.com/ru/post/1397285/


All Articles