Negative arguments for scipy.special.spherical_jn leads to nans
See original GitHub issuescipy.special.spherical_jn
seems to generate nan
s for negative input arguments, which does not seem to be prohibited and the documentation does not seem to warn against. For example, the following code
import numpy as np
from scipy.special import spherical_jn
n = 5
zs = np.linspace(-5, 5, 10)
print(spherical_jn(n, zs))
yields an output of
[ nan nan nan nan nan 5.03098996e-06 1.11092345e-03 1.17516973e-02 4.66525179e-02 1.06811161e-01]
Based on the reflection formula from DLMF, I used the following fix for my purposes
import numpy as np
from scipy.special import spherical_jn
def spherical_bessel(n, z):
return np.where(not isinstance(z, complex) and z<0, (-1)**n*spherical_jn(n, -z), spherical_jn(n, z))
zs = np.linspace(-5, 5, 10)
print(spherical_bessel(n, zs))
which gave the result
[-1.06811161e-01 -4.66525179e-02 -1.17516973e-02 -1.11092345e-03 -5.03098996e-06 5.03098996e-06 1.11092345e-03 1.17516973e-02 4.66525179e-02 1.06811161e-01]
I suspect that a similar, but more general fix can be used for a PR if this is deemed a legitimate issue.
(I’m using Python 3.7.7, numpy-1.21.1 and scipy-1.7.1)
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5 (3 by maintainers)
Thanks. Yeah, it seems like that’s why they weren’t added originally. The PR linked is ready then.
@czgdp1807 Although it doesn’t seem necessary, adding them seems nice for completeness and would be good if users need them. They also seem easy to implement by calling existing scipy.special functions, which is what a user who needs them would do anyway.