从 sympy.core.add.Add 转换为 numpy 复数 [英] Convert from sympy.core.add.Add to numpy complex number
本文介绍了从 sympy.core.add.Add 转换为 numpy 复数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有来自 Sympy 求解器的解决方案列表:
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
如何将此列表转换为具有正常复数值的单元格的 numpy 对象?
How can I convert this list to a numpy object with cells which are normal complex value?
推荐答案
可以调用内置函数 complex
在每个元素上,然后将结果传递给 np.array()
.
例如
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]
使用列表推导式和内置函数 complex
来创建 Python 复杂值列表:
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)]
使用与 numpy.array
的参数相同的表达式来创建一个复杂的 numpy 数组:
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 ])
或者,您可以使用 numpy.fromiter
:
In [29]: np.fromiter(z, dtype=complex)
Out[29]: array([ 1.+3.5j, 2.+3.j , 4.-5.j ])
这篇关于从 sympy.core.add.Add 转换为 numpy 复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文