Python : How to avoid numpy RuntimeWarning in function definition?

Question:

i designed a simple function to return a mathematical function which can be used to fit experimental data to it. The functions looks pretty much like the following:

def colecole_2(f,*p):
    term1=p[0] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[1], p[2])))
    term2=p[3] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[4], p[5])))
    return p[6]*(1-abs( term1+ term2))

Unfortunately I run into troubles with RunTimeWarnings as:

RuntimeWarning: overflow encountered in power
RuntimeWarning: overflow encountered in divide

due to values that are too large or small. I am not able to figure this problem out on my own though. Is there any way to redefine my function so it will pass without warnings?

Asked By: user1371788

||

Answers:

Use numpy.seterr to control what numpy does in this circumstance: http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

Use the warnings module to control how warnings are or are not presented: http://docs.python.org/library/warnings.html

Answered By: Mike Graham

You can use numpy.errstate which is a built-in context manager. This will let you set the err handing to be within the context of the with statement.

import numpy
# warning is not logged here. Perfect for clean unit test output
with numpy.errstate(divide='ignore'):
    numpy.float64(1.0) / 0.0

I had to do this recently when writing unit tests for some legacy python code.

Answered By: Jay P

To go around this, you could increase the precision by modifying the type of the array elements on which you call your function.

For example, if multiplying array a with large numbers as elements by a large floating point number raises an exception

RuntimeWarning: overflow encountered in multiply

then upon specifying the following

a = np.array(a, dtype=np.float128)

no warning occurs.

Answered By: alexs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.