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

Question:

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.

Asked By: Jesh Kundem

||

Answers:

You can use .real to get the real part of a complex 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

Answered By: Hit Box

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.

Answered By: Rahul Patel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.