Python - how to get only the real part of a complex number

Viewed 2222

I have the following code snippet, where the np.roots function will provide two complext numbers and one real number. I was able to extract the real root, however the output is always Complex. How can I change to only real number.

Cd = 0.88
coeff = [1, -3, (3+Cd**2), (Cd**2 - 1)]
roots = np.roots(coeff)
X = (roots[np.isreal(roots)]);
print (X)

The output is usually

[0.05944403+0.j]

However, how can I get only the following as output?

0.059444

The reason I am looking for that is, all my next calculations are also resulting complex numbers.

2 Answers

You can use .real to get the real part of an imaginary number

import numpy as np
Cd = 0.88
coeff = [1, -3, (3+Cd**2), (Cd**2 - 1)]
roots = np.roots(coeff)
X = (roots[np.isreal(roots)]);
print (X)
print (X.real) # print(X.imag)

additionally, python has .imag to get the imaginary part

I think you are looking for .real.

Cd = 0.88
coeff = [1, -3, (3+Cd**2), (Cd**2 - 1)]
roots = np.roots(coeff)
X = (roots[np.isreal(roots)]);
print (X.real)

Also, consider X.imag for the imaginary part.

Related