Search code examples
pythonarrayssympycomplex-numbersreal-number

How can I select only the real numbers from an array? (Python 3)


I want to find the vertical asymptote for:

f=(3x^3 + 17x^2 + 6x + 1)/(2x^3 - x + 3)

So I want to find the roots for (2x^3 - x + 3) so I wrote:

 import sympy as sy
 x = sy.Symbol('x', real=True)
 asym1 = sy.solve(2*x**3-x+3,x)
 for i in range(len(asym1)):
     asym1[i] = asym1[i].evalf()
 print(asym1)


The output was:

[0.644811950742531 + 0.864492542166306*I, 0.644811950742531 - 
0.864492542166306*I, -1.28962390148506]

So right now the only number that makes sense in the output is -1.289 and the complex numbers don't have any meaning.

My question is: How can I only select the real numbers so the output says:

asym1 = -1.28962390148506

Solution

  • you can do:

    asym1 = [n for n in asym1 if n.is_real][0]