Complex numbers: convert SymPy to numeric (I to 1j)

吃可爱长大的小学妹 提交于 2019-12-13 17:22:03

问题


using symbolic calculation in Python I have

import sympy
from cmath import *
from mpmath import arg, cplot

z = sympy.symbols('z')

fhandle='z**2'
g = lambda w: sympy.sympify(fhandle).evalf(subs={z: w})
g(1+2j)

# Returns: -3.0 + 4.0*I
# hence the next command fails, because I is expected to be 1j

cplot(g, [-3,3], [-3,3])

Crawling the web I only found this which will fix the matter for the print command, but will not work with cplot.

Any suggestions?


回答1:


One option is to wrap the result by calling complex:

>>> def g(w):
...     return complex(sympy.sympify(fhandle).evalf(subs={z: w}))
... 
>>> g(1+2j)
(-3+4j)

After which mpmath.cplot(g, [-3, 3], [-3, 3]) produces

Note that I've used a named function here. There's not much point to using a lambda if you're going to immediately give it a name anyhow.



来源:https://stackoverflow.com/questions/16716786/complex-numbers-convert-sympy-to-numeric-i-to-1j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!