How to find out if the Sympy variable is complex?

怎甘沉沦 提交于 2019-12-31 05:03:10

问题


I am writing a code which involves solving this equation

X = solve(Theta_Mod_Eqn*Ramp_Equation/(x+PT) - C, x)

I am using sympy library, now the equation has 7 roots few are complex and few are real. I am unable to segregate them because isinstance(i,complex) is always returning true

for i in X:
    if not isinstance(i,complex):
        if (i>-0.01 and i<maxSheaveDisp):
            A = i;

for one case i = -0.000581431210287302 - 0.2540334478167*I

In:i == complex
Out[39]: False

How to find out if the variable is complex?


回答1:


The set of real numbers is a subset of the set of complex numbers. So, every real number is a complex number. For example, 3 is a complex number.

The correct question to ask is how to find out if a root is real. For that, you can use i.is_real if i is a SymPy symbol:

for i in X:
    if i.is_real:
        if (i>-0.01 and i<maxSheaveDisp):
            A = i

One can also compare im(i) to 0: if im(i) == 0. This works for Python floats too.



来源:https://stackoverflow.com/questions/48854589/how-to-find-out-if-the-sympy-variable-is-complex

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