Ask Your Question
1

Numpy-array arguments of special functions in SageMAth

asked 2023-05-03 13:01:32 +0200

das_universum gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-03 21:33:51 +0200

slelievre gravatar image

updated 2023-05-04 14:41:18 +0200

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]])
edit flag offensive delete link more

Comments

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.

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

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-05-04 09:38:08 +0200 )edit

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

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

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2023-05-03 13:01:32 +0200

Seen: 115 times

Last updated: May 04 '23