pythonnumpynaninfinity

Why does `np.sum([-np.Inf, +np.Inf])` warn about "invalid value encountered in reduce"


python -c "import numpy as np; print(np.sum([-np.Inf, +np.Inf]))" 

gives

numpy\core\fromnumeric.py:86: RuntimeWarning: invalid value encountered in reduce
  return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
nan

I wonder why that is:

  1. There is no warning in

    python -c "import numpy as np; print(np.sum([-np.Inf, -np.Inf]))" 
    

    nor in

    python -c "import numpy as np; print(np.sum([+np.Inf, +np.Inf]))" 
    

    so it can't be the Infs.

  2. There is no warning in

    python -c "import numpy as np; print(np.sum([np.nan, np.nan]))"   
    

    so it can't be the NaN result.

What is it, then, and how can I avoid it? I actually like getting NaN as a result, I just want to avoid the warning.


Solution

  • The warning is fine, because Inf - Inf is mathematically undefined. What result would you expect?

    If you want to avoid the warning, use a filter as follows:

    import warnings
    
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=RuntimeWarning)
        res = np.sum([-np.Inf, np.Inf])