Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to avoid numpy RuntimeWarning in function definition?

Tags:

python

numpy

People also ask

How do you stop a runtime warning in Python?

Print the warning the first time it is generated from each module. Print the warning the first time it is generated. Following interactive session sets filter to default by simplefilter() function. In order to temporarily suppress warnings, set simplefilter to 'ignore'.

What is RuntimeWarning?

One warning you may encounter in Python is: RuntimeWarning: overflow encountered in exp. This warning occurs when you use the NumPy exp function, but use a value that is too large for it to handle.


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.


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


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.