Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement numpy.sin(x) / x where x might contain 0

Tags:

python

numpy

What I am doing now is:

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 is quite a lot of additional array operation. Is there a better way?

like image 510
eph Avatar asked Mar 31 '16 02:03

eph


People also ask

How do you write sin in NumPy Python?

sin() in Python. numpy. sin(x[, out]) = ufunc 'sin') : This mathematical function helps user to calculate trigonometric sine for all x(being the array elements).

Why is sin pi not 0 in Python?

Floating point rounding error. Pi cannot be represented exactly as a floating point number, so sin(pi) isn't going to be exactly zero.

Does NumPy sin take radians or degrees?

sin. Trigonometric sine, element-wise. Angle, in radians ( rad equals 360 degrees).

Does += work with NumPy arrays?

Numpy arrays are mutable objects that have clearly defined in place operations. If a and b are arrays of the same shape, a += b adds the two arrays together, using a as an output buffer.


1 Answers

You could use numpy.sinc, which computes 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
like image 123
Warren Weckesser Avatar answered Sep 17 '22 22:09

Warren Weckesser