Amund Jenssen
Amund Jenssen

Reputation: 39

sympy array of expressions to numpy array

I got a sympy array

sympyarray = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]])

and want to transform it into a numpy array

numpyarray=np.array([2/(dx**2*(np.exp(1j*theta) + 1)), -2*np.exp(-1j*theta)/dx**2, 2*np.exp(-1j*theta)/(dx**2*(np.exp(1j*theta) + 1))])

and wonder if there are any good way to do this?

My method has until now been the following:

  1. convert the complex " I " in sympyarray to "1j" using sympy.subs
  2. convert the sympy array into numpy array using

    numpyarray = sympyarray.tolist()

  3. inserting "np." before all the exp(1j*theta) in the printed numpyarray, since the .tolist() dont change the sympy exponential into a numpy exponential.

It surely must be an easier way?

Note: To my knowlage, lambdify is not the answer here. As I read the documentation, lambdify converts a sympy expression into a function that need numerical input? Or am I way off?

Upvotes: 1

Views: 1943

Answers (1)

asmeurer
asmeurer

Reputation: 91620

Use lambdify:

In [10]: expr = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]])

In [12]: f = lambdify([dx, theta], expr, 'numpy')

In [15]: f(np.array([1], dtype=complex), np.array([np.pi], dtype=complex))
Out[15]:
array([[[ 0. -1.63312394e+16j],
        [ 2. +2.44929360e-16j],
        [-2. +1.63312394e+16j]]])

Upvotes: 1

Related Questions