The best way to implement numpy.sin (x) / x, where x may contain 0

Now I do the following:

import numpy as np

eps = np.finfo(float).eps

def sindiv(x):
    x = np.abs(x)
    return np.maximum(eps, np.sin(x)) / np.maximum(eps, x)

But there are many additional operations with the array. Is there a better way?

+4
source share
3 answers

You can use numpy.sincthat calculates sin (pi x) / (pi x):

In [20]: x = 2.4

In [21]: np.sin(x)/x
Out[21]: 0.28144299189631289

In [22]: x_over_pi = x / np.pi

In [23]: np.sinc(x_over_pi)
Out[23]: 0.28144299189631289

In [24]: np.sinc(0)
Out[24]: 1.0
+5
source

In the numpy array notation (so you return the np array):

def sindiv(x):
    return np.where(np.abs(x) < 0.01, 1.0 - x*x/6.0, np.sin(x)/x)

Here I made the epsilon big enough for testing and used the first two members of the Taylor series to get closer. In practice, I would change 0.01 to a small multiple of yours eps(machine epsilon).

xx = np.arange(-0.1, 0.1, 0.001)
yy = sinxdiv(xx)
type(yy)

numpy.ndarray, ( , ) .

(.. ), , , , - "".

def sindiv(x):
    sox = np.zeros(x.size)
    for i in xrange(x.size):
        xv = x[i]
        if np.abs(xv) < 0.001: # For testing, use a small multiple of machine epsilon
            sox[i] = 1.0 - xv * xv / 6.0
        else:
            sox[i] = np.sin(xv) / xv
    return sox

pythonic, x , .

+1

How about resolving the div to zero and replacing NaN later?

import numpy as np

def sindiv(x):
    a = np.sin(x)/x
    a = np.nan_to_num(a)
    return a

If you do not want warnings, suppress them through seterr

Of course, use acan be eliminated:

def sindiv(x):
    return np.nan_to_num(np.sin(x)/x)
0
source

All Articles