Home > Back-end >  How to vectorize a function in python that includes a limit (e.g. sin(x)/x)
How to vectorize a function in python that includes a limit (e.g. sin(x)/x)

Time:01-22

I have a complex function that includes (sin(x)/x). At x=0, this function has a limit of 1, but when numerically evaluated is NaN.

This function is vectorized to get high performance when evaluating a large number of values, but fails when x=0.

A simplified version of this problem is shown below.

import numpy as np
def f(x):
    return np.sin(x)/x
x = np.arange(-5,6)
y = f(x)
print(y)

When executed, this returns:

... RuntimeWarning: invalid value encountered in true_divide return np.sin(x)/x

[-0.19178485 -0.18920062 0.04704 0.45464871 0.84147098 nan 0.84147098 0.45464871 0.04704 -0.18920062 -0.19178485]

This can be addressed by trapping the error, finding nan and substituting for the limit.

Is there a better way to handle a function like this?

Note: The function is more complex than sin(x)/x. The limit is know. Theuse of sinc is not an option. sin(x)/s is used to illustrate the problem.

CodePudding user response:

You could try to use true_divide with where to specify the place where you want to divide and out to pass in an out array that contains the result you expect at the places were you don't want to divide. Not sure if this is the most optimal solution but that would work. In code that should read liad

res = np.true_divide(sin(x), x, where=x!=0, out=np.ones_like(x))

CodePudding user response:

there's an implementation of numpy sinc that you can use.

CodePudding user response:

I'm used to this option while I'm doing my plots:

x = np.arange(-5, 6, dtype=float)
domain = x!=0
fill_with = np.nan
f = np.divide(np.sin(x), x, out=np.full_like(x, fill_with), where=domain)

You can customize any domain and value to fill with outside the domain.

  •  Tags:  
  • Related