Search code examples
matlabmathbessel-functions

Matlab custom spherical bessel function NaN at 0


I have a problem involved spherical Bessel functions of order 0. I wrote my own spherical Bessel function:

function js = sphbesselj(nu,x)
js = sqrt(pi ./(2* x)) .* besselj(nu + 0.5, x);
end

which seems to agree with Mathematicas inbuilt one for all my test cases. The problem is at nu or x =0. Mathematica correctly returns 1, but my MATLAB scrip returns NaN. How could I correct my code, so that if I feed in an array of say x = 0:1:5 I get the 1 for my first value, instead of

>> sphbesselj(0,x)
ans =
   NaN    0.8415    0.4546    0.0470   -0.1892   -0.1918

Is my custom function the best way to go about this?

Thanks


Solution

  • In fact, floating point values of x close to 0 also return Nan. You actually have three cases to possibly worry about. x = ±∞ results in NaN as well. Here's a vectorized function that handles those:

    function js = sphbesselj(nu,x)
        if isscalar(nu) && isscalar(x)
            js = 0;
        elseif isscalar(nu)
            js = zeros(size(x));
            nu = js+nu;
        else
            js = zeros(size(nu));
            x = js+x;
        end
        x0 = (abs(x) < realmin);
        x0nult0 = (x0 & nu < 0);
        x0nueq0 = (x0 & nu == 0);
        js(x0nult0) = Inf;          % Re(Nu) < 0, X == 0
        js(x0nueq0) = 1;            % Re(Nu) == 0, X == 0
        i = ~x0nult0 & ~x0nueq0 & ~(x0 & nu > 0) & (abs(x) < realmax);
        js(i) = sign(x(i)).*sqrt(pi./(2*x(i))).*besselj(nu(i)+0.5,x(i));
    end
    

    A useful resource when developing such functions is http://functions.wolfram.com. The page on the spherical Bessel function of the first kind has many useful relationships.