# Numpy-array arguments of special functions in SageMAth

Hi all,

I am struggling with realising how to get through the problem of computing e.g. bessel_K with an argument being given by a numpy array in order to make numerical computations much faster. The problem is when I set e.g. m = np.array([1,1],[1,1]]), then bessel_K(1,m) gives the error: unable to convert '[[11]\n[11]]' to a real number. How can this problem be resolved?

edit retag close merge delete

Sort by ยป oldest newest most voted

Many of Sage's functions are indeed not designed to work with NumPy arrays.

The error message can vary across versions of Sage.

One option is to use SciPy's Bessel functions instead of Sage's.

Example.

Sage and Python versions used in this example:

sage: print("{}, Python {}.{}.{}".format(version(), *sys.version_info[:3]))
SageMath version 9.8, Release Date: 2023-02-11, Python 3.10.8


Define a NumPy array:

sage: import numpy as np
sage: m = np.array([[1, 1], [1, 1]])


Error when using Sage's bessel_K with that NumPy array:

sage: bessel_K(1, m)
Traceback (most recent call last)
...
NotImplementedError: The Function bessel_K does not support numpy arrays as arguments


Success with SciPy's kn using an integer first argument:

sage: import scipy
sage: scipy.special.kn(1, m)
array([[0.60190723, 0.60190723],
[0.60190723, 0.60190723]])


SciPy's kv allows the first argument to be real and the second one to be complex:

sage: scipy.special.kv(m, 1j*m)
array([[-0.69122984-1.22712623j, -0.69122984-1.22712623j],
[-0.69122984-1.22712623j, -0.69122984-1.22712623j]])

more

Thank you for your answer! However, I personally have a more complicated situation in which I cannot use SciPy, as far as know. Specifically, I have an integrand of the form bessel_K(I*m1,m2), where I is imaginary unit, and m1 & m2 numpy arrays.

( 2023-05-03 21:38:23 +0200 )edit

You may also use Bessel functions as defined in Sage : try `Bessel?"...

( 2023-05-04 09:38:08 +0200 )edit

Thanks for your comment! Unfortunately, I get the same error as by using bessel_K.

( 2023-05-04 11:52:06 +0200 )edit