pythonnumpyprecision

Why does np.exp(1000) give an overflow warning but np.exp(-100000) not give an underflow warning?


On running:

>>> import numpy as np
>>> np.exp(1000)
<stdin>:1: RuntimeWarning: overflow encountered in exp

Shows an overflow warning. But then why does the following not give an underflow warning?

>>> np.exp(-100000)
0.0

Solution

  • By default, underflow errors are ignored.

    The current settings can be checked as follows:

    print(np.geterr())
    
    {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
    

    To issue a warning for underflows just like overflows, you can use np.seterr like this:

    np.seterr(under="warn")
    np.exp(-100000)  # RuntimeWarning: underflow encountered in exp
    

    Alternatively, you can use np.errstate like this:

    import numpy as np
    
    with np.errstate(under="warn"):
        np.exp(-100000)  # RuntimeWarning: underflow encountered in exp