First time here? Check out the FAQ!

Ask Your Question
1

Numpy-array arguments of special functions in SageMAth

asked 2 years ago

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?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 2 years ago

slelievre gravatar image

updated 2 years ago

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]])
Preview: (hide)
link

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 ( 2 years ago )

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2 years ago )

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

das_universum gravatar imagedas_universum ( 2 years ago )

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: 2 years ago

Seen: 314 times

Last updated: May 04 '23