[Numpy-discussion] runtime warning for where

alex argriffi at ncsu.edu
Sat Nov 16 08:36:45 EST 2013


On Sat, Nov 16, 2013 at 8:28 AM, David Pine <djpine at gmail.com> wrote:
> The program at the bottom of this message returns the following runtime warning:
>
> python test.py
> test.py:5: RuntimeWarning: invalid value encountered in divide
>  return np.where(x==0., 1., np.sin(x)/x)
>
> The function works correctly returning
> x = np.array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])
> y = np.array([ 1.        ,  0.84147098,  0.45464871,  0.04704   , -0.18920062,
>       -0.19178485, -0.04656925,  0.09385523,  0.12366978,  0.04579094,
>       -0.05440211])
>
> The runtime warning suggests that np.where evaluates np.sin(x)/x at all x, including x=0, even though the np.where function returns the correct value of 1. when x is 0.  This seems odd to me.  Why issue a runtime warning? Nothing is wrong.  Moreover, I don't recall numpy issuing such warnings in earlier versions.
>
> import numpy as np
> import matplotlib.pyplot as plt
>
> def sinc(x):
>    return np.where(x==0., 1., np.sin(x)/x)
>
> x = np.linspace(0., 10., 11)
> y = sinc(x)
>
> plt.plot(x, y)
> plt.show()

For what it's worth, you can see the different strategies that numpy
and scipy use to work around this warning.

https://github.com/numpy/numpy/blob/master/numpy/lib/function_base.py#L2662
https://github.com/scipy/scipy/blob/master/scipy/special/basic.py#L43

Numpy sinc uses a small number instead of zero.  Scipy sinc disables
the warning explicitly.



More information about the NumPy-Discussion mailing list