2

I have this list of solutions from Sympy solver:

In [49]: sol
Out[49]: 
[-1.20258344291917 - 0.e-23*I,
 -0.835217129314554 + 0.e-23*I,
 0.497800572233726 - 0.e-21*I]

In [50]: type(sol)
Out[50]: list

In [51]: type(sol[0])
Out[51]: sympy.core.add.Add

How can I convert this list to a numpy object with cells which are normal complex value?

Ohm
  • 2,312
  • 4
  • 36
  • 75

1 Answers1

6

You can call the builtin function complex on each element, and then pass the result to np.array().

For example,

In [22]: z
Out[22]: [1 + 3.5*I, 2 + 3*I, 4 - 5*I]

In [23]: type(z)
Out[23]: list

In [24]: [type(item) for item in z]
Out[24]: [sympy.core.add.Add, sympy.core.add.Add, sympy.core.add.Add]

Use a list comprehension and the builtin function complex to create a list of python complex values:

In [25]: [complex(item) for item in z]
Out[25]: [(1+3.5j), (2+3j), (4-5j)]

Use that same expression as the argument to numpy.array to create a complex numpy array:

In [26]: import numpy as np

In [27]: np.array([complex(item) for item in z])
Out[27]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])

Alternatively, you can use numpy.fromiter:

In [29]: np.fromiter(z, dtype=complex)
Out[29]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214