Search code examples
pythonfloating-pointfloating-point-exceptions

How to let a Python program raise an alarm whenever a floating-point overflow or underflow occurs?


I have a python program P that calls numpy, scipy and many other libraries in scientific computing. I can modify program P but cannot modify the libraries it calls.

Now I want the program P raises an alarm whenever a floating-point overflow or underflow occurs. How can I do that?

An example of overflow is to compute an exponential function e^x when x is large. But that exponential function is not something I can touch. It maybe called indirectly, so checking the return value or parameter of the function is not doable. Also there might be other numerical functions that cause overflow. So I am looking for a systematic way to detect floating-point overflow at run time.


Solution

  • Try using the method seterr.

    https://numpy.org/doc/stable/reference/generated/numpy.seterr.html

    import numpy as np
    
    np.seterr(over='raise')
    
    np.exp(1000000)