[Numpy-discussion] Unexpected RuntimeWarning

Bob Dowling rjd4+numpy@cam.ac...
Fri Nov 23 05:38:25 CST 2012


I have a simple function defined in the following snippet:

  --- start ---
import numpy

def chebyshev(x, m):
     '''Calculates Chebyshev functions of the first kind using the 
trigonometric identities.'''

     theta = numpy.where(
         numpy.abs(x)<=1.0,
         numpy.arccos(x),
         numpy.arccosh(numpy.abs(x))
         )

     y = numpy.where(
         numpy.abs(x)<=1.0,
         numpy.cos(m*theta),
         numpy.cosh(m*theta) * numpy.where(
             x > 0.0,
             1.0,
             -1.0
             )**m
         )

     return y


if __name__ == '__main__':
     x = numpy.linspace(-2.0, 2.0, 21)
     y = chebyshev(x,3)
     print(y)

  --- end ---


I'm using the numpy.where() call to extract only legal values for the 
circular and hyperbolic trigonometric functions.  But I still get 
warnings that I'm passing invalid anrguments:

--- start---

$ python3 demo.py
demo.py:8: RuntimeWarning: invalid value encountered in arccos
   numpy.arccos(x),
demo.py:9: RuntimeWarning: invalid value encountered in arccosh
   numpy.arccosh(numpy.abs(x))
[ -2.60000000e+01  -1.79280000e+01  -1.15840000e+01  -6.77600000e+00
   -3.31200000e+00  -1.00000000e+00   3.52000000e-01   9.36000000e-01
    9.44000000e-01   5.68000000e-01  -1.83697020e-16  -5.68000000e-01
   -9.44000000e-01  -9.36000000e-01  -3.52000000e-01   1.00000000e+00
    3.31200000e+00   6.77600000e+00   1.15840000e+01   1.79280000e+01
    2.60000000e+01]

  --- end ---

(I get the same with Python 2 so don't get excited about that.)


I'm guessing that numpy.where() is evaluating the complete arccos and 
arccosh arrays and therefore getting invalid arguments.

Now, I can turn off the warnings with numpy.seterr(invalid='ignore') but 
that's not what I would regard as good practice.

Is there a "numpythonic" way to address the issue?


More information about the NumPy-Discussion mailing list